22

Say I have a directory of files at

/home/user1/dir1

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

/dir1/file1
/dir1/file2

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

--strip-components 

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

Thanks!

24

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
  • 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
  • 1
    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
21

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.

5

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
2
tar -C /home/user1/dir -c .

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.