Ask.Cyberinfrastructure

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

bash

#1

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:

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

$ lower LiKeOmGTaCoS
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.


#2

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

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

And classic if then else statement

result=0

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

#3

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:

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

That would print out:

one
two

image