Linux: Adding Your Own Bash Shortcut Functions

When I’m using the command line on Ubuntu it’s often for very repetitive tasks for which I would have typed in the same endless command a thousand times if it weren’t for the CTRL-R search function that let’s me execute commands from the history list quickly by typing a part of it. There is one tiny drawback, however. There are some commands which are a subset of others, such as logging into a server via ssh to get a shell or to automatically execute a job on the same serer. Here’s an example:

ssh martin@xyz.com 

ssh martin@xyz.com '/home/martin/xyz.sh'

Both commands are identical at the beginning so as a consequence I sometimes have to type in CTRL-R a number of times before I get to the shorter one. There must be a better way to do this! And indeed there is as a colleague of mine recently showed me.

The solution to the problem is to put your own shell commands (functions) in the .bashrc file in your home directory. Instead of searching for the two commands above in the history buffer I would instead now type in two short commands:

msp

msbatch

The two commands above are declared in .bashrc as follows:

function msshell () {
  ssh martin@xyz.com
}

function msjob () {
 ssh martin@xyz.com '/home/martin/xyz.sh'
}

Once two two commands are in the bash config file, they are included each time you log-in. For testing purposes one can reload the .bashrc files as follows without logging-out and in again:

source ~/.bashrc

Functions are of course not limited to executing a single line of code. If you enjoy shell scripting the possibility are endless.

Yes, I know, this functionality has probably been in many Unix shells long before I was even born. But it’s still better to find out now than never. Enjoy!