Ant - Compress everything

By xngo on June 29, 2019

The Ant build file below will compress everything from the current directory into myProjectName_YYYY-MM-DD_HH.MM.SS.tar.gz, except files with the format myProjectName_*.tar.gz and the db directory.

<project basedir="." default="build" name="myProjectName">
 
  <tstamp><format property="DAY_TIME_NOW" pattern="yyyy-MM-dd_HH.mm.ss" /></tstamp>
 
  <target name="pack_code" description="Packing everything.">
    <tar compression="gzip" destfile="${ant.project.name}_${DAY_TIME_NOW}.tar.gz" 
      basedir="." 
      excludes="db/**, **/${ant.project.name}_*.tar.gz"  
    />
  </target>
 
  <!-- Or compress multiple specific files. -->
  <target name="compress_multiple_files">
    <tar compression="gzip" destfile="/path/to/my_archive.tar.gz">
      <tarfileset dir=".">
        <include name="my_file1.txt"/>
        <include name="my_file2.txt"/>
      </tarfileset>
    </tar>
  </target>
 
</project>

Note:

Don't use base="." attribute in <tar> if the base directory have a directory that contains a lot of files(>50 000). Otherwise, it will be very slow.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.