How to uncompress a tar.gz in another directory

UnixTarGzip

Unix Problem Overview


I have an archive

> *.tar.gz

How can I uncompress this in a destination directory?

Unix Solutions


Solution 1 - Unix

You can use the option -C (or --directory if you prefer long options) to give the target directory of your choice in case you are using the Gnu version of tar. The directory should exist:

mkdir foo
tar -xzf bar.tar.gz -C foo

If you are not using a tar capable of extracting to a specific directory, you can simply cd into your target directory prior to calling tar; then you will have to give a complete path to your archive, of course. You can do this in a scoping subshell to avoid influencing the surrounding script:

mkdir foo
(cd foo; tar -xzf ../bar.tar.gz)  # instead of ../ you can use an absolute path as well

Or, if neither an absolute path nor a relative path to the archive file is suitable, you also can use this to name the archive outside of the scoping subshell:

TARGET_PATH=a/very/complex/path/which/might/even/be/absolute
mkdir -p "$TARGET_PATH"
(cd "$TARGET_PATH"; tar -xzf -) < bar.tar.gz

Solution 2 - Unix

gzip -dc archive.tar.gz | tar -xf - -C /destination

or, with GNU tar

tar xzf archive.tar.gz -C /destination

Solution 3 - Unix

Extracts myArchive.tar to /destinationDirectory

Commands:

cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'

Solution 4 - Unix

You can use for loop to untar multiple .tar.gz files to another folder. The following code will take /destination/folder/path as an argument to the script and untar all .tar.gz files present at the current location in /destination/folder/path.

if [ $# -ne 1 ];
 then
 echo "invalid argument/s"
 echo "Usage: ./script-file-name.sh /target/directory"
 exit 0
fi
for file in *.tar.gz
do
    tar -zxvf "$file" --directory $1
done

Solution 5 - Unix

I'm unsure if this is a RedHat specific issue, but I had to move the -C to the front of the untar command so that the change directory executed ahead of the untar. Every other example I saw has it at the end, and for me would mean the archive was unpacked into the working dir. Example below:

tar -C /u00/app/oracle/product -xvf /var/tmp/oem-backup.tar.gz u00/app/oracle/product/OEM --strip-components=4

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMercerView Question on Stackoverflow
Solution 1 - UnixAlfeView Answer on Stackoverflow
Solution 2 - UnixMercerView Answer on Stackoverflow
Solution 3 - UnixjavaPlease42View Answer on Stackoverflow
Solution 4 - UnixRahulView Answer on Stackoverflow
Solution 5 - UnixIain HunterView Answer on Stackoverflow