How to Use tar Command in Linux: Syntax and Examples
The
tar command in Linux is used to create and extract archive files. Use tar -cf archive.tar files to create an archive and tar -xf archive.tar to extract it.Syntax
The basic syntax of the tar command is:
tar [options] [archive-file] [file or directory]
Here, options control the action (create, extract, list), archive-file is the name of the tar file, and file or directory specifies what to archive or extract.
bash
tar [options] [archive-file] [file or directory]
Example
This example shows how to create a tar archive named backup.tar from the documents folder and then extract it.
bash
tar -cf backup.tar documents tar -xf backup.tar
Common Pitfalls
Common mistakes include:
- Forgetting the
-foption, which specifies the archive file name. - Using
-c(create) and-x(extract) together, which is invalid. - Not specifying the correct path, causing unexpected files to be archived or extracted.
bash
tar -cf archive.tar file1 file2 # Correct way to create # Wrong: missing -f option # tar -c archive.tar file1 file2 # Wrong: mixing create and extract # tar -cxf archive.tar file1 # Right: extract # tar -xf archive.tar
Quick Reference
| Option | Description |
|---|---|
| -c | Create a new archive |
| -x | Extract files from an archive |
| -t | List contents of an archive |
| -f | Specify archive file name |
| -v | Verbose output showing files processed |
| -z | Compress archive with gzip |
| -j | Compress archive with bzip2 |
Key Takeaways
Use
-c with -f to create archives and -x with -f to extract them.Always specify the archive file name with
-f to avoid errors.Use
-v for verbose output to see what files are processed.Compress archives with
-z (gzip) or -j (bzip2) for smaller files.Avoid mixing create and extract options in the same command.