Bash tip: Extracting content from compressed files without the hassle

extraction col ford natasha de vere
Credit: flickr / Col_Ford-Natasha_de_Vere

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";;
  echo "no file called $1"

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.

Computerworld's IT Salary Survey 2017 results
Shop Tech Products at Amazon