In high performance computing, we generally work in a terminal, meaning using some shell. Have you ever seen these lines at the top of your “shell scripts?”
#!/bin/sh
or
#!/bin/sh
Those first lines are the interpreter lines - or an instruction for what program to use to run the script. If you look at the variable SHELL in your terminal, you likely will see the shell that you are using as we speak!
echo $SHELL
/bin/bash
There is a rich history of how the Unix shell became the “Bourne again” shell, or what we commonly refer to as bash.
So why bash?
The reason I want you to get excited about bash is because there are SO many things you can do with it that you would typically rely on a higher level language (python, R, etc.) to do. For example, you can trim strings, write functions to otherwise manipulate strings, calculate quantities, read files, count things… it’s a powerful language! Here is a one line function to make a string all lowercase:
Specifically, I want to share THE BASH BIBLE that is not only interesting, it’s fun and a great resource to learn from! So the next time you want to do some special thing from the command line? Ask yourself if you can do it with bash first, before you delve into requiring a higher level language dependency.
Agreed! Another useful example is to loop over a listing of files, or generally any terminal command that produces a list of things:
for file in $(ls $PWD);
do
echo $file;
done
That would generate an echo of all the files in the present working directory. You can imagine running a command instead and using the variable! Another simple loop is literally just a line of space separated strings, like this:
Here’s another one that came from nixCraft that I use all the time. Add this to your ~/.bashrc file to create a simple to use calculator:
calc() { echo "scale=2; $*" | bc -l; }
calc_full() { echo "$*" | bc -l; }
These lines create 2 functions:
calc: Results are trimmed to 2 decimal places
calc_full: Results are not trimmed
The usage is simple:
$ calc "1024*8" # Convert KB into MB
8192
$ calc "40*1.8+32" # Convert Celcius to Fahrenheit
104.0
$ calc "(2+2)*(2-2)" # You can also control the order of operation with ( )
0