Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
you need a " on the other side of $time as well. – gauteh Jun 4 '15 at 12:15
up vote 123 down vote accepted

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.

share|improve this answer
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
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
Yup, that worked much better. Thanks a bunch, appreciate it! – qwerty Sep 2 '12 at 17:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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