tar: create and extract archives
tar packs many files and directories into one archive file and unpacks them again, keeping names, permissions and times. Combined with compression it produces the familiar .tar.gz files.
The options you need
| Option | Meaning |
|---|---|
-c | Create an archive |
-x | Extract |
-t | List the contents |
-f file | The archive file (- for standard input/output) |
-v | Show each file |
-z, -J, --zstd | Compress with gzip, xz or zstd |
-a | Choose compression from the file name (GNU, BSD) |
-C dir | Change to dir first |
-p | Keep permissions when extracting (default for root) |
--exclude=PATTERN | Leave out matching files |
Create archives
tar -czf site.tar.gz site/ # gzip-compressed
tar -cJf logs.tar.xz /var/log/app # xz: smaller, slower
tar --zstd -cf data.tar.zst data/ # zstd: fast and small
tar -caf backup.tar.zst project/ # pick compression from the extension
tar -czf etc-$(date +%F).tar.gz -C / etc # store "etc/..." instead of "/etc/..."
tar -czf src.tar.gz --exclude='*.o' --exclude=.git src/
List and extract
tar -tf site.tar.gz # list contents (compression detected automatically)
tar -tvf site.tar.gz | less # with sizes and permissions
tar -xf site.tar.gz # extract into the current directory
tar -xf site.tar.gz -C /tmp/restore # extract somewhere else
tar -xf site.tar.gz site/index.html # extract one file
tar -xf backup.tar.gz --wildcards '*.conf' # extract matching files (GNU)
tar -xzf - < site.tar.gz # read the archive from standard input
Modern GNU and BSD tar detect the compression when extracting, so tar -xf works for .tar.gz, .tar.xz and .tar.zst alike. That works when reading a file; when GNU tar reads from a pipe, you still need -z, -J or --zstd.
An archive from someone else can contain absolute paths or ../ entries, or simply hundreds of files without a top directory. List it with tar -tf first, and extract into an empty directory with -C. GNU tar strips leading / by default.
Copy a directory tree over SSH
tar -czf - /srv/data | ssh backup@host 'cat > data.tar.gz' # archive straight to another host
tar -cf - -C /srv data | ssh host 'tar -xpf - -C /srv' # copy a tree; extract as root to keep owners too
For repeated copies, rsync is usually better because it transfers only changes.
Backups with tar
- Run as root with
--numeric-ownerto keep owners correct when restoring on another system. - Add
--xattrs --acls --selinux(GNU) to keep extended attributes, ACLs and SELinux labels. - Test that the archive is readable:
tar -tzf backup.tar.gz > /dev/null && echo OK.
Compression on its own is covered on the gzip page. On AIX, Solaris and HP-UX, the native tar may not support -z; use gzip -dc file.tar.gz | tar -xf - or install GNU tar.