Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
up vote 11 down vote accepted

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
share|improve this answer
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

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.

share|improve this answer

OK, I also found out that

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

also worked the way I wanted.

share|improve this answer
tar -C /home/user1/dir -c .
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.