Tar Command Cheatsheet
Tar Command Usage Guide
This cheatsheet provides essential commands for using the tar utility, a powerful tool for creating and extracting archive files on Unix-like systems. It covers common operations like compression, extraction, and advanced options.
Compressing Files with Tar
To compress files and create a .tar.gz archive, use the following command:
$ tar -zcvf my-archive.tar.gz ~/path/to/compress
-z: Compress the archive using gzip.
-c: Create a new archive.
-v: Verbose output, lists files as they are processed.
-f: Use archive file.
Extracting Archives with Tar
To extract files from a .tar.gz archive, use:
$ tar -xvf my-archive.tar.gz
-x: Extract files from an archive.
Excluding Files During Compression
You can exclude specific files or directories from being archived using the --exclude option. This is useful for backups to avoid temporary files, caches, or version control directories.
$ tar -zcvf backup-$(date +%F).tar.gz --exclude "~/personal/project/*/*.dat" --exclude "*.ldb" --exclude "*/.git/*" --exclude "*/.terraform/*" --exclude "*/site-packages/*" --exclude "*/node_modules/*" ~/workspace ~/Documents
This command creates a dated backup, excluding various file types and directories commonly found in development projects.
Archiving and Following Symlinks
By default, tar does not follow symbolic links. To archive the content that a symbolic link points to, use the -h option.
$ tar -cvhf archive.tar.gz /opt/app/current
-h: Follow symbolic links.
Combining Tar with Wget for Downloads
You can pipe the output of wget directly into tar to download and extract archives in a single step. This is efficient for fetching compressed files from URLs.
$ wget -q -O - https://github.com/sibprogrammer/xq/releases/download/v1.1.4/xq_1.1.4_linux_amd64.tar.gz | tar zxv
wget -q -O -: Downloads the file quietly (-q) and outputs it to standard output (-O -).
|: The pipe symbol sends the output of wget as input to tar.