Say I have a directory of files at


and I want to create a tar with only "dir1" as the leading directory:


I know I can first cd to the directory

cd /home/user1/
tar czvf dir1.tar.gz dir1

But when writing scripts, jumping from directory to directory isn't always favorable. I am wondering is there a way to do it with absolute paths without changing current directories?

I know I can always create a tar file with absolute paths INSIDE and use


when extracting but sometimes extra path names are extra private information that you don't want to distribute with your tar files.



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
  • 1
    Thanks. I didn't know that "-C" option has to be used before other options... I tried "tar -cvzf dir1.tar.gz dir1 -C /home/user1/" before but it didn't work. – Yan Nov 19 '09 at 22:15
  • 2
    Doesn't work: tar: dir: Cannot stat: No such file or directory (assuming dir1 is under /home/user1/) – tribbloid Mar 25 '18 at 3:00
  • 1
    @tribbloid See superuser.com/a/266429/100853 (I just faced the same problem) – Daniel F Jun 1 at 11:58

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.


OK, I also found out that

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

also worked the way I wanted.

  • Although wildcards like "*" then do not work – Curtis Yallop Jan 18 '18 at 19:37
tar -C /home/user1/dir -c .

I used bellow command to create tar for whole files in some directory,

tar -C ${filePath} -cvzf test.tar.gz $(ls ${filePath})

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.