Thursday, 6 October 2016

Bash aliases

What is an alias?

An alias is a bash command that runs one, or many other commands. An alias can also be created as a function and passed parameters.

How to add a new alias:

To create a new alias we want to add it in the correct bash startup file. In some instances (like the Ubuntu 16.04 LTS I am currently running) the default ~/.bashrc file already points us in the right place, it includes a ~/.bash_aliases file if one is present. This is a convenient way to seperate our aliases from the already full ~/.bashrc.

The alias:

Open the ~/.bash_aliases file with your editor of choice
--in terminal
$ nano ~/.bash_aliases

Create a new alias:
--in file ~/.bash_aliases
alias sftw='cd Software';

Close and re-open your terminal window or load the aliases with:
--in terminal
$ . ~/.bash_aliases

Now run the alias from the command line to see it in action:
--in terminal
$ sftw

You can also chain commands as you can in a normal terminal command by adding two ampersands (&&) in-between them:
--in file ~/.bash_aliases
alias startWeb1='cd Software/website1 && npm start'

If ~/.bash_aliases doesn't load

If your ~/.bashrc file does not contain a reference to the ~/.bash_aliases file you can add the reference like so:
--in terminal
$ nano ~/.bashrc

And add the following lines to the end:
--in file ~/.bashrc
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

Creating more complex aliases with functions

A function can take arguments and make multiple calls, for example:
--in file ~/.bash_aliases
gtst () {
        clear
        git branch 
        git status 
}
gtbr () {
        from=${2:-master}
        if ! `git checkout $1 &> /dev/null`; then
                `git checkout ${FROM}`
                `git checkout -b $1`
        fi
}
In the second function above we set a default value of "master" for variable 2 if no value exists. No alias entry is necessary, the function will be available.

Getting even fancier:

Let's wrap all these into a neat command called 'gt':
gt () {
        local argument2=$2
        local argument3=$3
        st () {
                clear
                git branch
                git status
        }
        br () {
                from=${argument3:-master}
                checkout=`git checkout ${argument2} 2>&1`
                if [ $? -eq 0 ]; then
                        echo "${checkout}"
                else
                        echo "`git checkout ${from}`"
                        `git checkout -b ${argument2}`
                fi
        }

        case "$1" in
                br) br;;
                st) st;;
        esac
}
Now we can call our new gt command from the command line as follows:
$ gt st
$ gt br existing-branch
$ gt br new-branch
$ gt br new-branch from-branch

No comments:

Post a Comment