Function and Alias use in bash
For a while now ive been using aliases to connect to machines. I alias a $hostname to xterm -T $hostname -e ssh $hostname &
. This means each connection gets a new fresh xterm. Of course doing an alias command for each host woudl be tedious so i have some magic in bash startup stuff.
bob@betty:~ >cat .bashrc [ -f ~/.bash_aliases ] && . ~/.bash_aliases PS1="\u@\h:\w >" PATH=$PATH:/usr/sbin:/usr/local/sbin:/sbin bob@betty:~ >cat .bash_aliases for MACHINE in `cat ~/.machines` do alias $MACHINE="xterm -T $MACHINE -e ssh $MACHINE &" done
Where .machines
is a list of machines one per line
Recently I have been connecting to machines which arnt in this list with ssh directly. This has the disadvantage that they dont get their own xterm and I have to start another xterm manually if I need another one. So I started to looking into aliasing ssh to the same thing. However, aliases arnt clever enough for this you need to use functions instead.
So I wrote a function to do what i wanted.
function ssh { xterm -T $1 -e ssh $1 & }
It then occured to me since this is just programming perhaps I can expand this to check to see if host is mentioned in .machines
and if it isnt add it. So I wrote a function
function testmachine { machine=`grep $1 ~/.machines` if [ "x$machine" = "x" ] then echo "not in ~/.machines adding" echo $1 >> ~/.machines source ~/.bash_aliases fi }
As you can see it also then sources ~/.bash_aliases
this makes sure that the current shell gets the new alias. I then added more to the ssh fucntion
function ssh { xterm -T $1 -e ssh $1 & testmachine $1 }
I then told my .bashrc
to source a new file called .bash_functions
which contains the two fucntions from above. And everything is now good.