In this article, we cover how to compress a directory in Linux. If there are a large number of files that need to be sent over a network then sending them as one file at a time isn’t something we do. You must have noticed that as well. When we share/copy a large file the process gets over perhaps within minutes. But, if there are a number of smaller files that as a group are of similar size to our large file. Copying smaller files takes more time.
On the hand, we can compress files irrespective of their size. As compressed files take much lesser space and that helps us transfer and store them faster. Therefore, it’s a great alternative to sharing and storing files. The only downside is we have to extract them later for use.
Though there are numerous tools in Linux that can help us compress directories. The command-line tool we cover here is tar.
How to Compress a Directory in Linux
With the help of the command-line tool, tar, we can manage archive files. Use the following syntax:
tar -zcvf compress-file.tar.gz /path/to/directory-compress
where, -z for using gzip,
-c to create an archive,
-v to list processed files,
and, -f for the archive file name.
Let’s understand it with the help of an example. To compress a directory: /dev/shm/backup/ as backup.tar.gz
Open a terminal and issue the following command:
tar -zcvf backup.tar.gz /dev/shm/backup
In conclusion, we have covered how to compress a directory in Linux.
Additional Info:
Once we have compressed the directory. How do we access or extract it? Although there are multiple use cases where one may wish to extract only one file from the archive or multiple files at once. One may also wish to remove some of its contents. All of that, we will cover in a separate article.
What we cover now is how to extract all the files in an archive. So, we continue with the above example – backup.tar.gz
To extract all the contents of the archive in the current directory:
tar -zxvf backup.tar.gz
Or, to extract all the contents of the archive in a specific directory:
tar -zxvf backup.tar.gz -C /dev/shm/new-dir
where -x is to extract the contents of an archive,
-C is to change the directory.