Unpacking a tar.gz archive

Files / Archives

#the archive to unpack
mkdir -p "data/sub"
echo "one" > "data/one.txt"
echo "two" > "data/sub/two.txt"
tar -czf "data.tar.gz" "data"
rm -r "data"

#x extracts, z uncompresses gzip; -C sets where, and the directory must exist
mkdir "tmp"
tar -xzf "data.tar.gz" -C "tmp"
text=$(< "tmp/data/sub/two.txt")
#text is "two"

#a name after the archive extracts that file only;
#--strip-components cuts the first directory off the paths
mkdir "flat"
tar -xzf "data.tar.gz" -C "flat" --strip-components 1 "data/one.txt"
[[ -f "flat/one.txt" ]] && stripped=true || stripped=false
#stripped is true

#a zip archive is unpacked by unzip: unzip data.zip -d tmp

echo "text is $text"
echo "stripped is $stripped"
rm -r "tmp" "flat" "data.tar.gz"