The tar command

an archiving utility 17 examples from the lessons of the IVski Linux Playground — try them in the terminal next to them.

Options in the examples

-f, --file=ARCHIVE
Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environment variable `TAPE'.
-v, --verbose
Verbosely list files processed. Each instance of this option on the command line increases the verbosity level by one.
-z, --gzip, --gunzip, --ungzip
Filter the archive through gzip(1).
-c, --create
Create a new archive. Arguments supply the names of the files to be archived.
-x, --extract, --get
Extract files from an archive. Arguments are optional.
-C, --directory=DIR
Change to DIR before performing any operations.
-t, --list
List the contents of an archive. Arguments are optional.
-j, --bzip2
Filter the archive through bzip2(1).
-J, --xz
Filter the archive through xz(1).

Examples

tar -cvf archive.tar directory/

Create archive

tar -czvf archive.tar.gz directory/

Create + gzip compress

tar -cjvf archive.tar.bz2 directory/

Create + bzip2 compress

tar -cJvf archive.tar.xz directory/

Create + xz compress

tar -xvf archive.tar

Extract

tar -xzvf archive.tar.gz

Extract gzip

tar -xjvf archive.tar.bz2

Extract bzip2

tar -xvf archive.tar -C /target/dir

Extract to directory

tar -tvf archive.tar
tar -tzvf archive.tar.gz
tar -czf "$BACKUP_DIR/backup-$DATE.tar.gz" "$SRC_DIR"
tar -czf ~/backups/docs-$(date +%F).tar.gz -C ~ documents

$(…) puts a command's output into another

tar -xzf /home/student/releases/site-v2.tar.gz -C /var/www/releases/v2
tar -czvf backup-$(date +%F).tar.gz .
tar -tzf /backups/FILE.tar.gz

List what's inside (nothing is extracted)

tar -tzf /backups/FILE.tar.gz | grep website

Narrow it down

tar -xzf /backups/FILE.tar.gz -C ~ projects/website

Extract just one directory into your home

Lessons that use tar

Related commands