Backup Your Files with 'tar' in Linux

The easiest way to back up your files is just copying. But if you have too many files to backup, copying and restoring may take too long time and it is not convenient. If there is a tool that can put many files into one file, the world will be better. Fortunately, 'tar' is used to create archive files. It can pack files or directories into a 'tar' file. It is like WinZip in Windows, but without compression.

How to create an archive file?

The most simple way to create an archive file with 'tar' is: tar -cf foo.tar file1 file2 ... Here, foo.tar is the name of the tar file you want and file1, file2... are the files you want to back up. The argument 'c' means 'create' and 'f' means 'filename'. After that, tar will generate foo.tar which contains file1, file2....

By the way, the suffix '.tar' is not necessary, it is just a good habit. Although you can specify the files you want to backup, the more usual usage of 'tar' is packing a directory, including its sub-directories and files: tar -cf foo.tar directory_name. So put your files into a directory before using tar is a good habit.

If you have installed gzip and bzip2 (almost all Unix/Linux include them), tar can call them directly to compress. i.e. create a '.tar.gz' or '.tar.bz2' file. The argument 'z' stands for 'gzip': tar -czf foo.tar.gz directory_name and 'j' means 'bzip2': tar -cjf foo.tar.bz2 directory_name. Since compression is a hard task for CPU, this will take more time. But it can save much disk space indeed.

Restoring

Restoring means extracting files from a tar file. To extract files into the current directory from a normal tar file (without compression), just use 'x' argument. For example: tar -xf foo.tar. If you want to extract to another directory, you need '-C' (uppercase) argument. For example, tar -xf foo.tar -C /opt/foo will put the files into /opt/foo directory (make sure you have enough permission to write /opt/foo).

If the tar file is compressed, you need know its format, gzip or bzip2. Usually you can know it through the file's suffix. To extract from '.tar.gz' file, use 'z' argument and to extract from '.tar.bz2', use 'j'. 'tar' will call gunzip or bunzip2 automatically.

tar -zxf foo.tar.gz
tar -jxf foo.tar.bz2

How to view a tar file?

For some reasons, you want to know what a tar file includes but you don't want to extract files from it. What you need is 't' argument. It will list the files and directories that a tar file contains:

tar -tzf foo.tar.gz

Some tricks

If the files you want to backup is too large or too many, it may take very long time. You can add '&' to make tar run in the background, so you can continue to do other work.

tar -czf foo.tar.gz foo &

If you like to print the file that tar is processing currently, you can use 'v' argument:

tar -xzvf foo.tar.gz

It will show a list of files on the screen.

Tags: