Last Updated: March 08, 2016
· ksmandersen

Extracting archives from the terminal easily

I often find my self downloading an archive from the terminal with some
obscure format for which I'm not quite sure what command to use for extraction.

# extract any time of compressed file
function extract {
    echo Extracting $1 ...
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2)   tar xjf $1  ;;
            *.tar.gz)    tar xzf $1  ;;
            *.bz2)       bunzip2 $1  ;;
            *.rar)       rar x $1    ;;
            *.gz)        gunzip $1   ;;
            *.tar)       tar xf $1   ;;
            *.tbz2)      tar xjf $1  ;;
            *.tgz)       tar xzf $1  ;;
            *.zip)       unzip $1   ;;
            *.Z)         uncompress $1  ;;
            *.7z)        7z x $1  ;;
            *)        echo "'$1' cannot be extracted via extract()" ;;
        echo "'$1' is not a valid file"

I found this shell function somewhere a while ago. This single function has saved
me countless of google lookups. Just paste into your bash_profile or where you keep
your shell commands.

Then all you need to do is calling the function with any archive you may wish like so:

$ extract some_weird_archive.tbz2

4 Responses
Add your response

You could easily condense all the tar commands to just

tar xvf <file.ext>

This works on tar.{bz2,xz,gzip,tbz2,tgz}

over 1 year ago ·

There is a tool for it

unp foo.ext
over 1 year ago ·

There is also atool with aunpack command. Not only it handles different types, it also creates a directory for extracted files if there are more than one in the archive root.

over 1 year ago ·

There's an attributed, extended and improved version for zsh here:

over 1 year ago ·