How to Create a Tar File in Linux: Simple Guide
To create a tar file in Linux, use the
tar command with the -cf options followed by the archive name and files or directories to include. For example, tar -cf archive.tar folder/ creates a tar file named archive.tar containing the folder directory.Syntax
The basic syntax to create a tar file is:
tar: the command to create or extract tar archives-c: create a new archive-f: specify the filename of the archivearchive.tar: the name you want for your tar filefiles_or_directories: the files or folders you want to include
bash
tar -cf archive.tar files_or_directories
Example
This example creates a tar file named backup.tar containing the directory myfolder.
bash
tar -cf backup.tar myfolder/
Common Pitfalls
Common mistakes include:
- Forgetting the
-foption, which causes tar to write to standard output instead of a file. - Not specifying the correct path to files or directories, resulting in empty or wrong archives.
- Using
-cfwithout-v(verbose) can make it hard to see what is being archived.
Correct usage example with verbose output:
bash
tar -cvf archive.tar folder/ # Wrong: tar -cf archive.tar (no files specified) # Wrong: tar -c folder/ (missing -f and filename)
Quick Reference
| Option | Description |
|---|---|
| -c | Create a new archive |
| -f | Specify archive filename |
| -v | Show progress (verbose) |
| -x | Extract files from archive |
| -t | List contents of archive |
Key Takeaways
Use
tar -cf archive.tar files to create a tar file.Always include the
-f option to specify the archive name.Add
-v for verbose output to see what is being archived.Make sure to specify correct file or directory paths to include.
Use
tar -tf archive.tar to list contents without extracting.