Compress a folder with tar?

  • 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.

  • Mat

    Mat Correct answer

    8 years ago

    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.

    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!

    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).

    Yup, that worked much better. Thanks a bunch, appreciate it!

    what does -f do? thanks.

    @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.`

    With recent versions of tar the uppercase `J` (instead of the `z`) will use the xz LZMA2 compression.

    Why sudo? If the current user has read access to the www directory, it's very likely that it also has read access to everything else.

    `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.

    Got thrown off by a message saying `Can't add archive to itself` but this worked. Would prefer to see this answer the question with more brevity.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM