In this tutorial, we will show you how to archive and compress files on Linux. Archives are a collection of files and directories that are stored in a single file. You should create archives when you want to store and preserve files that you rarely use or when you want to create portable backups. Moreover, it is common to compress the archives in order to reduce the file size, preserve storage space and speed up the data transfer and reduce the bandwidth load.
Let’s dive into some examples. Assume that you have the following structure of folders and subfolders that contain files.
tree
.
└── myfolder
├── mysubfolder1
│ └── mytxt1.txt
└── mysubfolder2
└── mytxt1.txt
We can archive the myfolder
by running the following command:
tar -cf myfolder.tar myfolder
Note that the “c” flag means to create a new archive and the “f” flag means to interpret the input from the file rather than from the default, which is standard input.
Now, if we run the command:
ls -ltr
total 16
drwxr-sr-x 4 theia users 4096 Feb 9 06:07 myfolder
-rw-r--r-- 1 theia users 10240 Feb 9 06:43 myfolder.tar
We will see that the myfolder.tar
has been created.
If we want to archive the folder as well as compress it, we can add the z
option like:
tar -czf myfolder.tar.gz myfolder
Again, we can see that the myfolder.tar.gz
has been created.
ls -ltr
total 20
drwxr-sr-x 4 theia users 4096 Feb 9 06:07 myfolder
-rw-r--r-- 1 theia users 10240 Feb 9 06:43 myfolder.tar
-rw-r--r-- 1 theia users 206 Feb 9 06:46 myfolder.tar.gz
We have also the option to see the content of an archive by running:
tar -tf myfolder.tar
myfolder/
myfolder/mysubfolder1/
myfolder/mysubfolder1/mytxt1.txt
myfolder/mysubfolder2/
myfolder/mysubfolder2/mytxt1.txt
We can unarchive an archive by running the command:
tar -xf myfolder.tar
Similarly, we can decompress a .tar.gz
file by running the same command:
tar -xf myfolder.tar.gz
We can compress a directory using the zip command as follows:
zip -r myfolder.zip myfolder
total 28
drwxr-sr-x 4 theia users 4096 Feb 9 06:07 myfolder
-rw-r--r-- 1 theia users 10240 Feb 9 06:43 myfolder.tar
-rw-r--r-- 1 theia users 206 Feb 9 06:46 myfolder.tar.gz
-rw-r--r-- 1 theia users 168 Feb 9 07:07 myfolder.zip
And we can decompress a zip file by running the unzip command:
unzip myfolder.zip