sodcalculator

10 Tech How-To

Tar Command in Linux: How It Works

Guide 10-32243 · Updated · Step by step

Tar is the standard Linux tool for bundling files and directories into a single archive, often called a tarball. It preserves the original file structure, permissions, and timestamps, making it essential for backups and distributing source code. This guide explains how tar works and shows you the exact commands to create, view, and extract archives.

What You’ll Need

  • A Linux system with the tar utility installed (it comes preinstalled on virtually all distributions).
  • Terminal access with sufficient permissions to read the files you want to archive and write to the destination directory.
  • Basic familiarity with the command line, such as navigating directories and running commands with options.

Step-by-Step

  1. Understand the basic syntax. The tar command follows this pattern: tar [options] [archive-file] [files-or-directories]. Options are single letters that can be combined, like -cvf or -xzf. The archive file name usually ends with .tar for uncompressed archives or .tar.gz / .tgz for gzip-compressed ones.
  2. Create an uncompressed archive. To bundle files into a tarball, use the -c (create), -v (verbose), and -f (file) options. For example, to archive the documents folder into backup.tar, run: tar -cvf backup.tar documents/. The verbose flag lists each file as it is added, which helps confirm the operation.
  3. Compress the archive with gzip. Add the -z option to compress the archive using gzip, which reduces size but takes more time. The command becomes tar -czvf backup.tar.gz documents/. The resulting file is a gzipped tarball, commonly used for software distribution.
  4. Use other compression algorithms. For better compression, use -j for bzip2 (backup.tar.bz2) or -J for xz (backup.tar.xz). These are slower but produce smaller archives. For example: tar -cJvf backup.tar.xz documents/.
  5. List the contents of an archive. Before extracting, check what is inside with -t (list) and -f: tar -tvf backup.tar.gz. This shows file names, sizes, and permissions without extracting anything.
  6. Extract an archive. Use -x (extract) with -f to unpack the archive in the current directory: tar -xvf backup.tar.gz. If the archive is compressed, tar usually detects the compression automatically, so you do not need to specify -z or -j in modern versions. To extract to a specific directory, add -C /path/to/dir: tar -xvf backup.tar.gz -C /tmp/restore.
  7. Extract specific files or directories. To pull out only certain items, list them after the archive name: tar -xvf backup.tar.gz documents/report.pdf. This is useful when you need just a few files from a large archive.
  8. Add files to an existing archive. Use -r (append) to add files to the end of an uncompressed archive: tar -rvf backup.tar newfile.txt. Note that this does not work with compressed archives; you must decompress and recompress them.
  9. Exclude files or directories. When creating an archive, skip certain paths with --exclude: tar -cvf backup.tar documents/ --exclude=documents/temp. You can use wildcards, like --exclude='*.log', to filter by pattern.
  10. Preserve permissions and ownership. By default, tar preserves permissions and timestamps. When extracting as root, it also preserves ownership. If you need to preserve extended attributes or ACLs, add --xattrs or --acls respectively. For most backups, the defaults are sufficient.

Common Mistakes

  • Forgetting the -f option. Without -f, tar sends the archive to standard output or reads from standard input, which can lead to confusing errors. Always include -f followed by the archive name.
  • Using absolute paths in archives. If you run tar -cvf backup.tar /home/user/documents, the archive stores the full path, and extracting it will overwrite files in /home/user/documents. Instead, navigate to the parent directory and use relative paths, like tar -cvf backup.tar documents.
  • Extracting into the wrong directory. By default, tar extracts into the current directory. If you are not careful, you can scatter files. Always use -C to specify a target directory.
  • Mixing up compression flags. Using -z with a bzip2-compressed archive will fail. Modern tar can auto-detect compression when extracting, so omit the compression flag during extraction.
  • Overwriting files unintentionally. When extracting, tar overwrites existing files by default. To avoid this, use --keep-old-files to skip existing files or --overwrite to force overwriting.

Tips

  • Use -v sparingly on large archives; the output can be overwhelming. Instead, use --totals to see a summary at the end.
  • To see the progress of a large extraction, add --checkpoint=1000 to print a message every 1000 files.
  • For backups, consider using --listed-incremental to create incremental backups that only store changed files. This requires a snapshot file to track state.
  • When creating archives for distribution, include a top-level directory so users do not get files dumped into their current folder. For example, archive myapp/ rather than the contents of myapp/.
  • Test your archive after creating it with tar -tvf to ensure it contains what you expect.

Troubleshooting

  • “Cannot open: No such file or directory” when creating an archive: The path you specified does not exist. Check the spelling and that the file or directory is accessible from your current location.
  • “This does not look like a tar archive” when extracting: The file is corrupted or not a tar archive. Check the file type with file archive.tar.gz. If it is not a tar file, you may have the wrong file.
  • “gzip: stdin: not in gzip format”: You tried to decompress a file that is not gzip-compressed. Use file to see the actual format, then extract accordingly (e.g., with -j for bzip2 or no compression flag).
  • Permission denied when extracting: You lack write permission in the target directory. Use sudo if appropriate, or extract to a directory you own.
  • Archive extracts but files have wrong ownership: When extracting as a non-root user, tar cannot set ownership to the original owner. Use sudo to preserve ownership, or accept that files will be owned by your current user.
  • Disk full during extraction: The archive is larger than the available space. Check with df -h and free up space or extract to a different drive.

Frequently Asked Questions

What does tar stand for?

Tar stands for “tape archive,” a name from its origin as a tool for writing data to magnetic tape. Today it is used mainly for file bundling and compression.

What is the difference between .tar and .tar.gz?

A .tar file is an uncompressed archive that just bundles files together. A .tar.gz file is a .tar archive that has been compressed with gzip, reducing its size. You can create both with the same command by adding the -z flag.

How do I compress a tar file after creating it?

You can compress an existing .tar file with gzip: gzip backup.tar will create backup.tar.gz. Alternatively, you can use bzip2 or xz in the same way. To decompress, use gunzip backup.tar.gz to get back the .tar file.

Can I use tar to compress a directory recursively?

Yes, tar automatically includes all subdirectories and files when you specify a directory. For example, tar -czvf archive.tar.gz /path/to/dir archives everything inside that directory.

How do I extract a tar file without overwriting existing files?

Use the --keep-old-files option: tar -xvf archive.tar --keep-old-files. This will skip files that already exist and report them, leaving your current files untouched.

Is tar safe for backups?

Tar is reliable for creating archives, but for backups you should also consider using a dedicated backup tool that handles incremental backups and encryption. Tar can be used with encryption tools like GPG, but it does not encrypt by itself. Also, tar is not ideal for backing up a system while it is running, as files may change during the archive process.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →