Extract tar or just a gzipped file on Linux


Mon, 23 March 2020

Quite simply, compressing and decompressing files on Linux is incredibly easy, albeit that developers and sysadmins seem to be forever searching the web for the commands.


To decompress (untar) a tar.gz archive:

$ tar -xzf archive.tar.gz

If you've got a gz (gzipped) file, the command would be:

$ gunzip file.gz

That's it. Not too complicated whatsoever.


Tired of typing the entire thing? Add it to your .bash_profile as a lazy alias:

decompresstar() {
 TAR_GZ=$(echo $1 | grep -o '.......$')
 FILE_GZ=$(echo $1 | grep -o '...$')
 if [ "$TAR_GZ" = ".tar.gz" ]; then
  tar -xzf $1
 elif [ "$FILE_GZ" = ".gz" ]; then
  gunzip $1
 else
  echo "Not a .tar.gz or .gz file."
 fi
}
alias ungz=decompresstar

That's it! Easy. Next time you want to decompress an archive or file, just issue:

# For a .gz file:
ungz ./a-file.gz 
# Or, for an archive:
ungz ./an-arvhive.tar.gz