How to create tar archive in a different directory?

The easy way, if you don't particularly need to use -C to tell tar to change to some other directory, is to simply specify the full path to the archive on the command line. Then you can be in whatever directory you prefer to create the directory structure that you want inside the archive.

The following will create the archive /var/www/file.tar.gz and put file1 from the current directory (whatever that happens to be) in it, with no in-archive path information.

tar czf /var/www/file.tar.gz file1

The path (to either the archive, the constituent files, or both) can of course also be relative. If file1 is in /tmp, you are in /var/spool and want to create the archive in /var/www, you could use something like:

tar czf ../www/file1.tar.gz /tmp/file1

There's a million variations on the theme, but this should get you started. Add the v flag if you want to see what tar actually does.


I think, it should be:
tar czf file.tar.gz -C /var/www/ file1

Which works for me. It tells to change directory and then choose file.


I turn the compressed data into a stream (-) and easily rename and locate (>) whereever I choose (Also I always tar the relative path (./) so it's easier to deal with when uncompressing)

tar -cvf - ./dir-to-compress/* > /location-of-new-file/filename.tar

Tags:

Tar