How to tar a file in Linux using command line
I am a new Linux user. How can I create a tar file in Linux operating systems using the command line option?
Introduction: A Linux tarball (“tar.gz” or “tar.bz2” file ) is nothing but a system file format that combines and compresses multiple files. Tarballs are common file format on a Linux operating systems. Tarballs are often use for distribution of software/media or backup purposes. This page shows how to tar a file in Linux using the Linux tar command line option.
How to tar a file in Linux using command line
The procedure is as follows to tar a file in Linux:
- Open the terminal app in Linux
- Compress an entire directory by running tar -zcvf file.tar.gz /path/to/dir/ command in Linux
- Compress a single file by running tar -zcvf file.tar.gz /path/to/filename command in Linux
- Compress multiple directories file by running tar -zcvf file.tar.gz dir1 dir2 dir3 command in Linux
How to create tar a file in Linux
Say you want to compress an entire directory named /home/css/data/:
$ tar -czvf file.tar.gz /home/css/data/
To compress multiple directories and files, execute:
$ tar -czvf file.tar.gz /home/css/data/ /home/css/backup/ /home/vivek/.accounting.db
One can use bzip2 compression instead of gzip by passing the -j option to the tar command:
$ tar -cjvf file.tar.bz2 /home/css/data/
Where,
- -c : Create a new archive
- -v : Verbose output
- -f file.tar.gz : Use archive file
- -z : Filter the archive through gzip
- -j : Filter the archive through bzip2
How to exclude directories and files when using tar
You can exclude certain files when creating a tarball. The syntax is:
$ tar -zcvf archive.tar.gz --exclude='dir1' --exclude='regex' dir1
For example, exclude ~/Downloads/ directory:
$ tar -czvf /nfs/backup.tar.gz --exclude="Downloads" /home/css/
How do I view files stored in an archive?
Now you have an archive, to list the contents of a tar or tar.gz file using the tar command:
$ tar -ztvf file.tar.gz
$ tar -jtvf file.tar.bz2
How do I extracting an archive?
You can extract an archive or tarball with the tar command. The syntax is:
$ tar -xzvf file.tar.gz
$ tar -xjvf file.tar.bz2
Want to extract the contents of the archive into a specific directory such as /home/css/backups/? Try passing the -C DIR option:
$ tar -xzvf my.tar.gz -C /home/css/backups/
$ tar -xjvf archive.tar.bz2 -C /tmp/
- -x : Extract files from an archive
- -t : List the contents of an archive
- -v : Verbose output
- -f file.tar.gz : Use archive file
- -C DIR : Change to DIR before performing any operations
- --exclude : Exclude files matching PATTERN/DIR/FILENA