sandra_henrystocker
Unix Dweeb

Bash tip: Extracting content from compressed files without the hassle

How-To
Mar 12, 20152 mins

If you work with file archives that come in many different “flavors”, you might find this little trick to be a handy one. Add a function to your .bash_profile that runs the proper extraction command based on the file’s extension(s). This will keep you from ever having to scratch your head to make sure you’re selecting the right options for any of these commands. Add a “v” (for verbose) to the tar commands in the list if you want to see the files listed as they are being extracted.

extract ()
{
if [ -f $1 ] ; then
  case $1 in
    *.tar.gz)  tar xzf $1;;
    *.gz)      gunzip $1;;
    *.tar)     tar xf $1;;
    *.tgz)     tar xzf $1;;
    *.tar.bz2) tar xjf $1;;
    *.bz2)     bunzip2 $1;;
    *.rar)     rar x $1;;
    *.tbz2)    tar xjf $1;;
    *.zip)     unzip $1;;
    *.Z)       uncompress $1;;
    *)         echo "can't extract from $1";;
  esac
else
  echo "no file called $1"
fi
}

The function verifies that the file provided as an argument exists and then selects the appropriate command to decompress it or extract its contents based on the file extensions. Note that you have to order the file names in a way that ensures that the files with double extensions (like .tar.gz) are listed before their single extension counterparts (like .gz) so that you’re applying all of the correct arguments.

sandra_henrystocker

Sandra Henry-Stocker was a programmer, Linux systems administrator, security engineer and Linux journalist for most of her 30-year career. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she's chasing the bears away from her bird feeders. Tune into her 2-Minute Linux video tutorials and take command of your command line.

More from this author