Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

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

I thought tar archive.tar /users/mylocation would work, but it doesn't. How can I do that?

share|improve this question
10  
grep the 'man' like tar --help | grep directory – Ujjwal Singh May 8 '14 at 18:01
5  
@UjjwalSingh I would not search help or manpages like that... Enter man COMMAND then press / and type your search phrase. To search multiple manpages, enter apropos PHRASE or man -K PHRASE. – Six Feb 13 '15 at 19:20
    
Also, -C, --directory DIR\n change to directory DIR should rather be described as change output directory to DIR (will fail if DIR doesn't exist). Thanks @Mich. See also @Bryan_Larsen's answer. – valid Jul 13 '15 at 10:21
up vote 443 down vote accepted

To extract an archive to a directory different from the current, use the -C, or --directory, tar option, as in

tar -xf archive.tar -C /target/directory

Note that the target directory has to exist before running that command (it can be created by mkdir /target/directory).

Read the manual page (command: man tar) for other options.

share|improve this answer
2  
Thank u! It works! – goovim May 27 '11 at 1:42
5  
I read the man page, but couldn't figure out what to search for. Thanks for this answer! – Topher Fangio Apr 24 '13 at 20:41
39  
You have to create the directory manually though. – Michelle May 16 '13 at 10:01
31  
The number of times I've had to look this up is getting a little ridiculous. – ConsultStan Jul 29 '14 at 13:16
1  
If it's a larger file, when you run the command, all you get is no output for several seconds or even minutes while it's working. You can fix this by adding the -v flag (verbose mode) which lists the name of each file as it extracts it. – IQAndreas May 7 '15 at 6:15

Note that if your tarball already contains a directory name you want to change, add the --strip-components=1 option:

tar xf archive.tar -C /target/directory --strip-components=1
share|improve this answer
    
This combo of -C with --strip-components is more what I was looking for, and definitely hard to know what to search for in the man pages. More like an intuitive "extract into this dir and not the one in the tarball" – Brian May 2 at 16:36

Combining the previous answers and comments:

To simply extract the contents and create target directory if it is missing:

mkdir -p /target/directory && tar xf archive.tar -C /target/directory

To extract and also remove the root(first level) directory in the zip

mkdir -p /target/directory && tar xf archive.tar -C /target/directory --strip-components=1
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.