tar: How to create a tar file with arbitrary leading directories w/o 'cd'ing to parent dir

Solution 1:

tar -C changes directory

tar -C /home/user1/ -cvzf dir1.tar.gz dir1

btw, handy one for keeping track of changing directories... use pushd and popd.

pushd .
cd /home/user1
tar cvfz dir1.tar.gz
popd

Solution 2:

With gnu tar, you can create an archive with a different base directory than the actual with:

tar -c --transform 's,^\.,mybasedir,' .

Just adapt the sed expression to your needs.


Solution 3:

OK, I also found out that

tar -czvf file1.tar.gz /home/user1/dir1/../dir1

also worked the way I wanted.


Solution 4:

tar -C /home/user1/dir -c .