37

I would like to untar an archive e.g. "tar123.tar.gz" to directory /myunzip/tar123/" using a shell command.

tar -xf tar123.tar.gz will decompress the files but in the same directory as where I'm working in.

If the filename would be "tar233.tar.gz" I want it to be decompressed to /myunzip/tar233.tar.gz" so destination directory would be based on the filename.

Does anyone know if the tar command can do this?

Jorre
  • 17,273
  • 32
  • 100
  • 145

4 Answers4

37
tar -xzvf filename.tar.gz -C destination_directory
czerasz
  • 13,682
  • 9
  • 53
  • 63
Jorg B Jorge
  • 1,109
  • 9
  • 17
36

With Bash and GNU tar:

file=tar123.tar.gz
dir=/myunzip/${file%.tar.gz}
mkdir -p $dir
tar -C $dir -xzf $file
Randy Proctor
  • 7,396
  • 3
  • 25
  • 26
  • 1
    the problem here is that I don't know what the filename will be. It will be a versioned file so today it may be 1.tar.gz but tomorrow it might be 2.tar.gz. Is there a way to just say "file=what-ever-in-/home/user" ? – Jorre Jun 01 '10 at 16:16
  • 1
    You're going to have to know it somehow. If they sort, you can use something like `file=$(ls -1 $pattern | tail -1)`. – Randy Proctor Jun 01 '10 at 16:57
4

You can change directory before extracting with the -C flag, but the directory has to exist already. (If you create file-specific directories, I strongly recommend against calling them foo.tar.gz - the extension implies that it's an archive file but it's actually a directory. That will lead to confusion.)

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
2

Try

file=tar123.tar.gz
dir=/myunzip/$(basename $file .tar.gz)   # matter of taste and custom here
[ -d "$dir" ] && { echo "$dir already exists" >&2; exit 1; }
mkdir "$dir" && ( gzip -d "$file | ( cd "$dir" && tar xf - ) )

If you're using GNU tar you can also give it an option -C "$dir" which will cause it to change to the directory before extracting. But the code above should work even with a Bronze Age tar.

Disclaimer: none of the code above has been tested.

Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533