In system administration, it is often necessary to pack and compress a group of files. The main advantages are:
- Improved memory utilization
- Easier transportation
- Reduced download times
- And more...
The compression process generally involves the following two steps:
- Creation of Archive File
- Application of Compression Algorithms on the Archive File
We can group multiple files and directories into a single archive file using the tar command.
tar stands for tape archive.
To create a tar file containing specific files:
tar -cvf demo.tar file1.txt file2.txt file3.txtTo include all files in the current directory:
tar -cvf demo.tar *To view the contents of a tar file:
tar -tvf demo.tarTo extract the contents of a tar file:
tar -xvf demo.tarThere are multiple compression and decompression algorithms available:
- gzip - Fast but with less compression power
- bzip2 - Slower but provides higher compression power
$ gzip demo.tarThis command creates a compressed file demo.tar.gz.
$ gzip -d demo.tar.gz
# or
$ gunzip demo.tar.gzThis command restores the original demo.tar file.
$ bzip2 demo.tarThis creates a compressed file demo.tar.bz2.
$ bunzip2 demo.tar.bz2To create and compress a tar file in one command:
$ tar -cvzf demo.tar.gz *.txt- The
zoption compresses the file. - This creates
demo.tar.gz, which is already compressed.
To uncompress and extract:
$ tar -xvzf demo.tar.gzInstead of z, use j for bzip2 compression:
$ tar -cvjf demo.tar.bz2 *.txt- The
joption compresses the file. - This creates
demo.tar.bz2, which is already compressed.
To uncompress and extract:
$ tar -xvjf demo.tar.bz2Example for creating a backup of the user home directory:
$ pwd
/home/durgasoft
$ tar -cvzf backup.tar *
$ mkdir newhome
$ mv backup.tar newhome
$ cd newhome
$ tar -xvzf backup.tar