views:

145

answers:

4

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?

+1  A: 

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
+1  A: 

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
+2  A: 

With Bash and GNU tar:

file=tar123.tar.gz
dir=/myunzip/${file%.tar.gz}
mkdir -p $dir
tar -C $dir -xzf $file
Randy Proctor
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
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
+1  A: 

tar -xzvf filename.tar.gz -C destination_directory

Jorg B Jorge