Tar Command in Unix with Examples

The archive format preserves the directory structure, and the file system attributes such as permissions and dates.

Tar Syntax:

tar [function] [options] [paths]

Tar options:

The tar command supports the following functions:

  • tar -c: Create a new archive.
  • tar -A: Append a tar file to another archive.
  • tar -r: Append a file to an archive.
  • tar -u: Update files in an archive if the one in the filesystem is newer.
  • tar -d: Find the diff between an archive and the filesystem.
  • tar -t: List the contents of an archive.
  • tar -x: Extract the contents of an archive.

While specifying the function, the ‘-‘ prefix is not required, and the function can be followed by other single letter options.

Some of the supported options include:

  • -j: Read or write archives using the bzip2 compression algorithm.
  • -J: Read or write archives using the xz compression algorithm.
  • -z: Read or write archives using the gzip compression algorithm.
  • -a: Read or write archives using the compression algorithm determined by the archive file name.
  • -v: Perform the operations verbosely.
  • -f: Specify the file name for the archive.

Examples:

Create an archive file containing file1 and file2

$ tar cvf archive.tar file1 file2

Create an archive file containing the directory tree below dir

$ tar cvf archive.tar dir

List the contents of archive.tar

$ tar tvf archive.tar

Extract the contents of archive.tar to the current directory

$ tar xvf archive.tar

Create an archive file containing the directory tree below dir and compress it using gzip

$ tar czvf archive.tar.gz dir

Extract the contents of the gzipped archive file

$ tar xzvf archive.tar.gz

Extract only the given folder from the archive file

$ tar xvf archive.tar docs/work

Extract all “.doc” files from the archive

$ tar xvf archive.tar –-wildcards ‘*.doc’

Conclusion

The archive format of Tar Command in Unix preserves the directory structure, and the file system attributes such as permissions and dates.