Writing simple functions in bash shell
Did you know you could also enrich your bash environment with functions accepting parameters? They nicely complement aliases and shortcuts already presented in previous tips like Bash Terminal keyboard shortcuts and Handy Bash Shell Aliases,
Defining a function is easy. Just type the following in your terminal, or include it in your ~/.bashrc if you plan to keep it in your environment.
foo() { arg1=$1 arg2=$2 # code here ... }
Additional parameters passed as arguments to a function can be retrieved as $1, $2, .... etc...
In order to call a function, type its name followed by the desired parameters
foo my_arg_1 my_arg_2
For example, here is how I implemented a function named interactive to start an interactive session on a given number of nodes and duration:
interactive() { echo starting interactive job of $1 min on $2 nodes on debug queue salloc --time=$1 -N $2 -p debug srun --pty bash -i }
just typing
interactive 30 2
will start an interactive job of 30 minutes using 2 nodes of Shaheen