256

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?

  • you need a " on the other side of $time as well. – gauteh Jun 4 '15 at 12:15
352

To tar and gzip a folder, the syntax is:

tar czf name_of_archive_file.tar.gz name_of_directory_to_tar

The - is optional. If you want to tar the current directory, use . to designate that.

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

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

This would have created 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.

  • 1
    This is perfect, thank you. I have one tiny issue though. After creating a tar file of /var/www, it is placed within /var/www directories in the tar file. Here's the code i'm using now sudo tar -czf ~/www_backups/$time.tar /var/www/" Imagine i have a file called test.txt inside /var/www. After making a tar copy of the file, when i extract it it will be placed inside /var/www directories. Does that make sense? I hope it does, kinda hard to explain. I will check for BZip2 support, thanks for the suggestion! – qwerty Sep 2 '12 at 17:27
  • 1
    That's why you first cd to the directory you want to package, then tar cf file.tar . - that last . instead of specifying the full path will make the paths inside the archive relative to the current directory. You could also use the -C option for tar (look at the man page). – Mat Sep 2 '12 at 17:29
  • 1
    Yup, that worked much better. Thanks a bunch, appreciate it! – qwerty Sep 2 '12 at 17:33
  • 3
    @Qwertylicious -f (from man page) Read the archive from or write the archive to the specified file.The filename can be - for standard input or standard output. – Kolob Canyon Dec 27 '16 at 20:02
  • 1
    sudo was in the question, didn't change or question that. Having the backup target directory restricted to root isn't a bad idea though. – Mat Feb 26 '18 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.