Tuesday, July 23, 2013

HOWTO Compress a Directory on Linux?

How to Compress a Linux Directory?


To compress files or directories under Linux, GNU tar command is the best for this work. It can also be user remotely.

To Create and Compress the archive, you need to use tar command as follows:

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

For example, you have directory called /home/ximunix/blog and you would like to compress this directory then you run the following command:

ximena@anneke:~$ tar -zcvf ximunix_blog-1-jul-2013.tar.gz /home/ximunix/blog

The command above will create an archive file called ximunix_blog-1-jul-2013.tar.gz in your current directory (You can run the command "pwd" to check in which directory you are currently on).

If you wish to restore your archive then you need to use following command (it will extract all files in your current directory):

ximena@anneke:~$ tar -zxvf ximunix_blog-1-jul-2013.tar.gz

Where,
    -x: Extract files

If you wish to extract files in particular directory, for example in /tmp then you need to use following command:

ximena@anneke:~$ tar -zxvf ximunix_blog-1-jul-2013.tar.gz -C /tmp
ximena@anneke:~$ cd /tmp
ximena@anneke:~$ ls -l



How do I use tar command over secure ssh session?


The GNU version of the tar utility can be used through the network over ssh session.
The following command backups /home/ximunix/blog directory to the "bazinga" host (IP 192.168.1.101) over ssh session.

ximena@anneke:~$ tar zcvf - /home/ximunix/blog | ssh root@bazinga "cat > /backup/ximunix-blog.tar.gz"
OR
ximena@anneke:~$ tar zcvf - /home/ximunix/blog | ssh root@192.168.1.101 "cat > /backup/ximunix-blog.tar.gz"

You can also use the "dd" command for clarity purpose:
ximena@anneke:~$ tar cvzf - /home/ximunix/blog | ssh root@192.168.1.101 "dd of=/backup/ximunix-blog.tar.gz"

You can restore tar backup over ssh session:
ximena@anneke:~$ cd /
ximena@anneke:~$ ssh root@192.168.1.101 "cat /backup/ximunix-blog.tar.gz" | tar zxvf -


NOTE: If you wish to use the above command in a cron job, consider SSH keys to get rid of the passwords.