HowTo: Extract Archives [tar|gz|bz2|rar|zip|7z|tbz2|tgz|Z]

A small note about how to unpack and uncompress the most popular types of archives from the Linux command line.

Unpack [tar|tar.gz|tgz|tar.bz2|tbz2] Files in Linux

Use the following commands to extract TAR archives compressed with GZIP and BZIP2:

$ tar xvf file.tar
$ tar xvzf file.tar.gz
$ tar xvzf file.tar.tgz
$ tar xvjf file.tar.bz2
$ tar xvjf file.tar.tbz2

Uncompress [zip|rar|bz2|gz|Z|7z] Files in Linux

Use the following commands to uncompress archives or files, compressed with ZIP, GUNZIP, RAR, BUNZIP2, COMPRESS and 7Z programs:

$ unzip file.zip
$ gunzip file.gz
$ unrar x file.rar
$ bunzip2 file.bz2
$ uncompress file.Z
$ 7z x file.7z

Extract Archives with Shell Function

You can create a bash shell function as follows (add to your ~/.bashrc):

function extract {
 if [ -z "$1" ]; then
    # display usage if no parameters given
    echo "Usage: extract ."
 else
if [ -f $1 ] ; then
        # NAME=${1%.*}
        # mkdir $NAME && cd $NAME
        case $1 in
          *.tar.bz2) tar xvjf ../$1 ;;
          *.tar.gz) tar xvzf ../$1 ;;
          *.tar.xz) tar xvJf ../$1 ;;
          *.lzma) unlzma ../$1 ;;
          *.bz2) bunzip2 ../$1 ;;
          *.rar) unrar x -ad ../$1 ;;
          *.gz) gunzip ../$1 ;;
          *.tar) tar xvf ../$1 ;;
          *.tbz2) tar xvjf ../$1 ;;
          *.tgz) tar xvzf ../$1 ;;
          *.zip) unzip ../$1 ;;
          *.Z) uncompress ../$1 ;;
          *.7z) 7z x ../$1 ;;
          *.xz) unxz ../$1 ;;
          *.exe) cabextract ../$1 ;;
          *) echo "extract: '$1' - unknown archive method" ;;
        esac
else
echo "$1 - file does not exist"
    fi
fi
}

Source: https://github.com/xvoland/Extract

Reload .bashrc file.

$ . ~/.bashrc

Now use extract command for unpacking and uncompressing the most popular archive types:

$ extract file.rar
$ extract file.tar.gz2
$ extract file.7z