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/vivek/data/: $ tar -czvf file.tar.gz /home/vivek/data/ To compress multiple directories and files, execute: $ tar -czvf file.tar.gz /home/vivek/data/ /home/vivek/pics/ /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/vivek/data/ Where,
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/vivek/
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/vivek/backups/? Try passing the -C DIR option: $ tar -xzvf my.tar.gz -C /home/vivek/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
The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.