How do I do <insert thing here> in bash?



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?”




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

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:

lower() {
    printf '%s\n' "${1,,}"

$ lower LiKeOmGTaCoS

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.


It’s also very simple to use loops in BASH:

  • Simple for loop
for node in compute{1..10}; do
  ssh $node 'hostname -s'
  • Simple while loop
while /bin/true; do
  echo "looped ${count} times"
  let count=${count}+1
  sleep 10

And classic if then else statement


if [[ "$result" == "0" ]];then
  echo "Success"
  echo "Fail"


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); 
    echo $file; 

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:

$ for thing in "one" "two";
        echo $thing 

That would print out: