If you use bash a fair amount, you probably have some aliases set up. However, have there been times you wish you had some more control over the functionality of your alias?

Let’s examine one example: a bash alias and a bash function for extracting a file.

With an alias, we can easily abstract out the complicated tar command to simply extract.

alias extract='tar -xvzf'

Now we can type extract file.tar.gz or extract file.tgz and the command will extract the file. We can even specify output directories!

But what if we can’t rely on our downloaded file to have .tar.gz/.tgz extensions? Well in that case, a function for extract makes more sense!

function extract {
 if [ -z "$1" ]; then
    # display usage if no parameters given
    echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>"
 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
}

Now we can call extract without worrying about our file extension! We can just trust that the function will do exactly what it’s meant to.

So how can I start using bash functions?

First, import a file called .bash_functions in your .bashrc.

# Functions.
# These are like aliases, but can take arguments
# All functions are in ~/.bash_functions for modularity

if [ -f ~/.bash_functions ]; then
    . ~/.bash_functions
fi

Now you can either download my .bash_functions file as a starting point, or create your own at ~/.bash_functions!

Note: You must restart terminal or type source .bashrc in your terminal to start using the new bash functions.