Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This doesn't work:

tar xf /tmp/foo.tar.gz foo/bar
tar: foo/bar: Not found in archive

It's not obvious to me what would do this beyond extracting it in place and moving the files over.

share|improve this question
add comment

3 Answers

up vote 14 down vote accepted

From man tar:

     -C directory
         In c and r mode, this changes the directory before adding the
         following files.  In x mode, change directories after opening the
         archive but before extracting entries from the archive.

i.e, tar xC /foo/bar -f /tmp/foo.tar.gz should do the job. (on FreeBSD, but GNU tar is basically the same in this respect, see "Changing the Working Directory" in its manual)

share|improve this answer
3  
I reccommend to test this behaviour with non-GNU versions of tar. Solaris manual page only mentions this option in combination of add and replace operations. Being curious I've tested it with an extract operation. Solaris' tar did not issue any error or warning and extracted the archive in the current folder =:-/ –  ktf Nov 1 '11 at 16:57
add comment

Doing:

(cd foo/bar ; tar xf /tmp/foo.tar.gz )

would do the job.

Basically, what is does is spawning a new shell (the parentheses), in this subshell, change directory to foo/bar and then untar the file.

You can change the ; by a && to be sure the cd works fine.

share|improve this answer
1  
Wow that you can start a shell just like that is pretty cool! I had no idea you could do that. –  Kit Sunde Nov 15 '11 at 14:11
add comment

if you want to extract an tar archive elsewhere just cd to the destination directory and untar it there:

 mkdir -p foo/bar
 cd foo/bar
 tar xzvf /tmp/foo.tar.gz

The command you've used would search the file foo/bar in the archive and extract it.

share|improve this answer
add comment

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.