Tar Command - Archive Utility for Linux & Unix

Learn to use the tar command for archiving and compressing files on Linux and Unix systems. Explore common tar commands for backup, extraction, and deletion.

Tar Command Examples

Understanding the Tar Command

The tar command is a powerful utility used on Unix-like operating systems for creating, manipulating, and extracting archive files. It's often used in conjunction with compression utilities like gzip or bzip2 to create compressed archives (tarballs).

Common Tar Operations

Creating Compressed Archives

This example demonstrates how to back up the current user's HOME directory using tar with gzip compression. Permissions are preserved, and the filename format includes the user ID, group ID, and date.

# tar
# GNU version of the tar archiving utility

# An approach to backing up the current user's HOME, using tar(1) and Gzip
# compression. Permissions (modes) will be preserved. The filename format will
# be: UID:GID_DATE.tgz
#
# Replace 'DEVICE' with whichever device is applicable to you, but note that it
# must be in the '/media/USER' (where USER is the username) directory, else
# this won't work, unless you edit the formatting section of `printf`.
tar -czvpf "$(printf '/media/%s/%s/%d:%d_%(%F)T.tgz' "$USER" 'DEVICE' ${UID:-`id -u`} ${GID:-`id -g`} -1)" "$HOME"

Deleting Files from Archives

This command shows how to delete a specific file ('xdm') from a non-compressed archive. For compressed archives, you would typically decompress, delete, and then recompress.

# Delete file 'xdm' from the archive given to the `-f` flag. This only works on
# non-compressed archives, unfortunately, but those can always be uncompressed
# first, then altered with the `--delete` flag, after which you can recompress.
tar --delete -f xdm_edited.tar.gz xdm

Extracting Archives to a Specific Directory

This example illustrates how to extract the contents of a tarball to a specified destination directory using the -C flag. If no destination is provided, the current working directory is used.

# Extract the contents of the given archive (which is not compressed) to the
# destination given to the `-C` flag; not many seem to know of this flag.
#
# If a destination (path given to `-C`) is not provided, the CWD will be used.
tar -C /mnt -xvf Tarball.tar

Further Resources