Monday, 4 May 2020

Functions in aliases for bash

Thought i'd share a little nugget.

So i do a few commands in linux that are repetitive in nature, so i often alias them out so i'm lazy and don't have to type as much.
For instance, one of my repetitive commands is `git grep`, which is a great tool for going through your git repo to search those reg expressions.
So in my ~/.bashrc, i have
alias ggrep="git grep"
Now, all i do is ggrep <my search>

Something i learn't today however, is passing an argument to an alias.
My work has a lot of test boxes scattered around connected to different gear, so i ssh a lot to these. since the are all nicely formatted to tb<something a rather>, i decided i would now like to replace ssh tb0933 with tb 0933.
To do this is easy enough, but unlike a standard bash shell, we can't pass in the variable and just access like $x. Instead what we have to do is to create a function, and then call it.
So in the very simple case of the above my command equates to
alias tb='function ssh_tb=() { ssh tb$@; }; ssh_tb'
So expanding on this, we define the function ssh_tb() which when called, will execute the command ssh tb$@, and then at the end of this, we call it.


No comments:

Post a comment