30

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!

Yan
  • 453
  • 1
  • 4
  • 6

5 Answers5

28

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.

Christophe Drevet
  • 1,962
  • 2
  • 17
  • 25
28

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
Philip Reynolds
  • 9,751
  • 1
  • 32
  • 33
  • 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
  • 3
    Doesn't work: tar: dir: Cannot stat: No such file or directory (assuming dir1 is under /home/user1/) – tribbloid Mar 25 '18 at 03:00
  • 1
    @tribbloid See https://superuser.com/a/266429/100853 (I just faced the same problem) – Daniel F Jun 01 '21 at 11:58
5

OK, I also found out that

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

also worked the way I wanted.

Yan
  • 453
  • 1
  • 4
  • 6
2
tar -C /home/user1/dir -c .
Michael Graff
  • 6,588
  • 1
  • 23
  • 36
0

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

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