There are large number of archive file formats – .zip, .tar.gz, .tar, .gz, .7zip, .rar, etc etc..

I find it difficult to remember the command line options for extracting different archive file formats. So, I wrote a bash function which given a archive filename as an input extracts it.

Here’s the function :

extract () {
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 ;;
*) echo "'$1' cannot be extracted via extract ()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}

This function is pretty self explanatory. But as it is not powerful. It becomes the ultimate tool for extractive archive files if you copy this function in you bashrc file (~/.bashrc).

Now you can simply extract any file like this:


$extract test.tar.gz

Hope you like this function.

Note: This function doesn’t work with files have space in its name. I didn’t waste time in solving this issue as I normally don’t use such filenames. If any of you solve this issue, please do let me know. I would include it with your name in this post. :D



6 Comments to “Extract all Archive File Format With Just One Command in Linux”

  1. You are now listed on FAQPAL | January 28th, 2009 at 12:41 am

    Extract all Archive File Format With Just One Command in Linux…

    Extracting archived files easily using linux….

  2. Geoserv | January 28th, 2009 at 4:32 am

    Wow, thanks for compiling and sharing.

  3. hemanth | February 1st, 2009 at 12:39 am

    I made the changes for the script to work for file names with spaces , i tired its working fine here , hope its bugs free.

    #!/bin/bash
    extract()
    {
    SAVEIFS=$IFS
    IFS=$(echo -en “\n\b”)
    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 ;;
    *) echo “‘$1? cannot be extracted via extract ()”;;
    esac
    else
    echo “‘$1? is not a valid file”
    fi
    IFS=$SAVEIFS
    }

  4. Patrick | February 2nd, 2009 at 6:23 pm

    Also google for “unball” script. Provides similar functionality as long as you have the proper decompression program installed.

  5. Marc | October 28th, 2009 at 5:44 pm

    >> This function doesn’t work with files have space in its name

    The solution is very simple: just put double-quotes around every appearance of “$1″, e.g.
    if [ -f "$1" ] ; then
    case “$1″ in
    *.tar.bz2) tar xjf “$1″ ;;

    … and so on

  6. spsneo | October 28th, 2009 at 10:11 pm

    @Marc

    Thanks for your hint.
    I will update the blog accordingly.

Leave a Comment