≡ Menu

How to backup an entire directory on Linux?

The question – I have a large directory with several sub-directories. Is there a way to backup the entire directory recursively into a file which I can store on another file system?

There are two commands that are helpful in this case. The first one is called tar and the second is called gzip. The command tar can create an archive of all of your files in a directory and the command gzip can perform compression to reduce the file size.

How to backup an entire directory?

The command to create an archive of all of your files in the current directory is as follows:

tar -cvf backup.tar *

The -c argument says that you should create a new tar file. The -v command instructs tar to be verbose i.e. list each file that is added to the tar file. The -f argument is used to instruct tar to create a file called backup.tar i.e. give a file name to the archive file.

This command will create backup.tar from all the files in the current folder and all its sub-folders.

Now once you have your backup.tar file, you can reduce the size of the file by compressing its contents:

gzip backup.tar

This will create a new compressed file called backup.tar.gz.

How to restore files from the backed-up file?

Now that you have your backup.tar.gz file, you should transfer it to another box or another file system. Once you do that, you may need to restore the files on the new machine.

To do this, first you must uncompress the file:

gzip -d backup.tar.gz

This command will uncompress the file and create a file called backup.tar. The -d argument instructs gzip to uncompress or inflate the file.

To expand backup.tar, use the following command:

tar -xvf backup.tar

This will create the same directory structure that you originally had when you created backup.tar. That -x argument instructs tar to extract (or inflate) the archive (as compared to the -c command which instructs tar to create a file (deflate)).

Comments on this entry are closed.