tar: create and extract archives

Updated November 2026

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.

tar -c [options] -f archive files ... # create tar -x [options] -f archive [files ...] # extract tar -t [options] -f archive # list

The options you need

OptionMeaning
-cCreate an archive
-xExtract
-tList the contents
-f fileThe archive file (- for standard input/output)
-vShow each file
-z, -J, --zstdCompress with gzip, xz or zstd
-aChoose compression from the file name (GNU, BSD)
-C dirChange to dir first
-pKeep permissions when extracting (default for root)
--exclude=PATTERNLeave 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.

Look before you extract

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

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.