Linux Backup – How to Compress a Folder with Tar

backuplinuxtar

I'm trying to compress a folder (/var/www/) to ~/www_backups/$time.tar where $time is the current date.

This is what I have:

cd /var/www && sudo tar -czf ~/www_backups $time"

I am completely lost and I've been at this for hours now. Not sure if -czf is correct. I simply want to copy all of the content in /var/www into a $time.tar file, and I want to maintain the file permissions for all of the files. Can anyone help me out?

Best Answer

To tar and gzip a folder, the syntax is:

tar czf name_of_archive_file.tar.gz name_of_directory_to_tar

The - with czf is optional.

If you want to tar the current directory, use . to designate that.

To construct filenames dynamically, use the date utility (look at its man page for the available format options). For example:

cd /var/www &&
tar czf ~/www_backups/$(date +%Y%m%d-%H%M%S).tar.gz .

This will create a file named something like 20120902-185558.tar.gz.

On Linux, chances are your tar also supports BZip2 compression with the j rather than z option. And possibly others. Check the man page on your local system.

Related Question