Saturday, November 13, 2010

Compress files using tar Command

SkyHi @ Saturday, November 13, 2010
How do I compress and backup files using tar command to another directory on same computer or another Linux computer under Ubuntu Linux?

First, open up a terminal under Ubuntu Linux. Some directories such as /etc require root permissions to read and write for backup. So you may need to run tar command using sudo command. In this example backup, /etc and your /home/vivek to /backup directory, enter:
$ sudo mkdir /backup
$ sudo tar -zcvpf /backup/files.backup.Nov_6_2009.tar.gz /etc/ /home/vivek
Where,

* z : Compress the backup file with 'gzip' to make it smaller.
* c : Create a new backup archive called /backup/files.backup.Nov_6_2009.tar.gz.
* v : Verbose mode, the tar command will display what it's doing to the screen.
* p : Preserves the permissions of the files put in the archive for restoration later.
* f /backup/files.backup.Nov_6_2009.tar.gz: Specifies where to store the backup, /backup/files.backup.Nov_6_2009.tar.gz is the filename used in this example.

How Do I Exclude Certain Files or Directories?

You can exclude all *.mp3 stored in /home/vivek/music directory with --exclude option:
$ sudo tar --exclude='/home/vivek/music/' -zcvpf /backup/files.backup.Nov_6_2009.tar.gz /etc/ /home/vivek
Another example (exclude ~/music/ and ~/Downloads/*.avi files):
$ sudo tar --exclude='/home/vivek/music/' --exclude='/home/vivek/Downloads/*.avi' -zcvpf /backup/files.backup.Nov_6_2009.tar.gz /etc/ /home/vivek
How Do I See a List Of Files Stored In Tar Ball or an Archive?

Type the following command:
$ sudo tar -ztvf /backup/files.backup.Nov_6_2009.tar.gz
Where,

* t: List the contents of an archive.

How Do I Restore Files?

You can use the command as follows to restore everything in / directory:
$ sudo tar -xvpzf /backup/files.backup.Nov_6_2009.tar.gz -C /
OR
$ cd /
$ sudo tar -xvpzf /backup/files.backup.Nov_6_2009.tar.gz
Where,

* -x: Extract the files.
* -C / : Extract the files in / directory.

In this example, you are restoring to the /delta directory.
$ sudo tar -xvpzf /backup/files.backup.Nov_6_2009.tar.gz -C /delta
How Do I Backup Files To a Remote Server Called backup.example.com?

Type the command as follows to backup /etc/ and /home/vivek directories to a remote system called backup.example.com:
$ sudo -s
# ssh user@backup.example.com "mkdir /backup"
# tar zcvpf - /etc/ /home/vivek | ssh user@backup.example.com "cat > /backup/files.backup.Nov_6_2009.tar.gz"
How Do I Restore Backup From a Remote System to Local Ubuntu Box?

Type the command
$ sudo -s
# cd /
# ssh user@backup.example.com "cat /backup/files.backup.Nov_6_2009.tar.gz" | tar zxpvf -

REFERENCES
http://www.cyberciti.biz/faq/ubuntu-howto-compress-files-using-tar/