This post will guide you how to compress a whole directory including subdirectories using tar command from the command line in Linux operating system. How do I compress a whole directory using tar command at the shell prompt in Linux system.
Tar Command
GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manipulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine.
The useage of Tar command are as followss:
Traditional usage
tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...]
UNIX-style usage
tar -A [OPTIONS] ARCHIVE ARCHIVE tar -c [-f ARCHIVE] [OPTIONS] [FILE...] tar -d [-f ARCHIVE] [OPTIONS] [FILE...] tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...] tar -r [-f ARCHIVE] [OPTIONS] [FILE...] tar -u [-f ARCHIVE] [OPTIONS] [FILE...] tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...]
GNU-style usage
tar {--catenate|--concatenate} [OPTIONS] ARCHIVE ARCHIVE tar --create [--file ARCHIVE] [OPTIONS] [FILE...] tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...] tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --append [-f ARCHIVE] [OPTIONS] [FILE...] tar --list [-f ARCHIVE] [OPTIONS] [MEMBER...] tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...] tar --update [--file ARCHIVE] [OPTIONS] [FILE...]
Compressing a Whole Directory
If you want to compress a whole directory to backup files in your Linux system, and you can use tar command to archive and compress the specified directory. You need to pass the “-zcvf” option to the tar command to compress and archive a whole directory. For example, you want to compress a directory called mydir under your current working directory. and you can use the following command:
$ sudo tar -zcvf mydir.tar.gz ./mydir
Outputs:
[devops@mydevops mydir]$ ls
myfile1 myfile2 myfile3 myfile4
[devops@mydevops mydir]$ cd ..
[devops@mydevops ~]$ tar -zcvf mydir.tar.gz ./mydir/
./mydir/
./mydir/myfile1
./mydir/myfile2
./mydir/myfile3
./mydir/myfile4
[devops@mydevops ~]$ ls my*
mydir.tar.gz myshell.sh mytask.yml
Note:
-z: Compress the desired file/directory using gzip
-c: Stand for create file (output tar.gz file)
-v: To display the progress while creating the file
-f: Finally the path of the desire file/directory to compress
If you want to de-compress the above archive file, and you need to pass the “-zxvf” option to the tar command, type:
$ tar -zxvf mydir.tar.gz
Outputs:
[devops@mydevops ~]$ tar -zxvf mydir.tar.gz
./mydir/
./mydir/myfile1
./mydir/myfile2
./mydir/myfile3
./mydir/myfile4
Note:
-x: Stand for extract file (input tar.gz file)
Conclusion
You should know that how to compress a whole directory using tar command in your CentOS or RHEL or Ubuntu system.