Compressing a Linux/UNIX directory is one of the recurrent system administrator’s activity. It is useful to backup files, email all files, or even to share feveral files you have created to friends. Technically, it is called as a compressed archive. GNU tar command is the best for this kind of activities.
Command syntax:
tar -zcvf archive-name.tar.gz directory-name
Where,
- -z : Compress archive using gzip program
- -c: Create archive
- -v: Verbose i.e display progress while creating archive
- -f: Archive File name
Example, you have a directory called /home/sami/files and you would like to compress this directory then you can type tar command as follows:
$ tar -zcvf files-18-08-2019.tar.gz /home/sami/files
Above command will create an archive file called files-18-08-2019.tar.gz
in current directory.
If you wish to extract your archive then you need to use the following command:
$ tar -zxvf files-18-08-2019.tar.gz
Where,
- -x: Extract files
If you wish to extract files in particular directory, for example in /tmp then you need to use the following command:
$ tar -zxvf files-18-08-2019.tar.gz -C /tmp
$ cd /tmp
$ ls -
A note about non gnu/tar command
The above syntax use GNU tar command for compressing and uncompressing tar files. If your system does not use GNU tar, you can still create a compressed tar file, via the following syntax:
tar -cvf - file1 file2 dir3 | gzip > archive.tar.gz
How do I use tar command over secure ssh session?
The GNU version of the tar archiving utility (and other old version of tar) can be use through network over ssh session. Do not use telnet command, it is insecure. You can use Unix/Linux pipes to create actives. Following command backups /wwwdata directory to dumpserver.nixcraft.in (IP 192.168.1.201) host over ssh session.
The default first SCSI tape drive under Linux is /dev/st0. You can read more about tape drives naming convention used under Linux here.
# tar zcvf - /wwwdata | ssh root@dumpserver.nixcraft.in "cat > /backup/wwwdata.tar.gz"
OR# tar zcvf - /wwwdata | ssh root@192.168.1.201 "cat > /backup/wwwdata.tar.gz"
Output:
tar: Removing leading `/' from member names /wwwdata/ /wwwdata/n/nixcraft.in/ /wwwdata/c/cyberciti.biz/ .... .. ... Password:
You can also use dd command for clarity purpose:
# tar cvzf - /wwwdata | ssh root@192.168.1.201 "dd of=/backup/wwwdata.tar.gz"
It is also possible to dump backup to remote tape device:
# tar cvzf - /wwwdata | ssh root@192.168.1.201 "cat > /dev/nst0"
OR you can use mt to rewind tape and then dump it using cat command:
# tar cvzf - /wwwdata | ssh root@192.168.1.201 $(mt -f /dev/nst0 rewind; cat > /dev/nst0)$
You can restore tar backup over ssh session:# cd /
If you wish to use above command in cron job or scripts then consider SSH keys to get rid of the passwords.
# ssh root@192.168.1.201 "cat /backup/wwwdata.tar.gz" | tar zxvf -