Chapter 6 BASH Scripts
Until now, we have been executing all BASH commands on the command line. This is perfectly fine for small commands, however, for long and complicated BASH pipelines, we might want to save our work as a BASH script. A BASH script is a plain text file which contains a series of commands. Anything we can run on the command line can be put in a script, and the other way around.
Saving what we do as scripts allows us to reuse our work on new data sets, to share analysis pipelines with others and - most importantly - to remember later what we have actually done!
Writing scripts in very easy. Let’s have a look at a simple example, a script that prints “Hello world!”:
A BASH script always starts with the line #!/bin/bash. The #! in here is called “shebang”. It marks the beginning of a script. Right after the shebang is the path to the program (interpreter) that should be used to run the script. In our case, shebang tells the computer to use /bin/bash to run the script, which is simply the BASH shell. If our script contained python code instead, this line would need to be modified, such that the computer would interpret the code as python.
To wrap up: each BASH script starts with #!/bin/bash to tell the computer that the following code must be interpreted as BASH code.
The rest of the file contains the commands that BASH should execute, in our example printing “Hello world!”. Nothing changes compared to the normal command line. If needed, comments can be added to the script. Everything after a # will be ignored by BASH (except for the shebang, of course). We can thus modify our script and add a comment:
Let’s now discuss how we can write such a BASH script. For this, we will review three common approaches.