Writing a bash script

Bash scripts are text files that are saved as .sh files.

She bangs the drums

(Great song by The Stone Roses)

The first line of a bash script must be a shebang. Shebang is a combination of # (bash) and ! (bang) followed by the bash shell path (the location of the bash tool in the file system):
#!/bin/bash
Shebang tells the shell to execute the script via bash shell and shows the shell the path to the bash interpreter.

You can find your bash shell path using the command:
which bash

The remaining lines

The shebang line is followed by all the commands you want to include in the script. They take on exactly the same format that they have when executed one by one on the command line.

Do not keep your comments to yourself

Indeed, it is strongly advised to add comments to your script so that others (and even you after a few weeks or months after the analysis) can figure out what the hell you were doing. Comments start with a # in a bash script e.g.
#This is a comment albeit not a useful one
Any line in the script that begins with a # will be ignored by the bash interpreter.

People have to open your script to see the comments, if they don’t look in the script they will not see them. Sometimes you have info that you want the users of your script to see. A command that is worth mentioning in this context is echo to send messages from the script to the screen (similar to a print command in other programming languages), e.g. when you include the following line in your script:
echo "That's all folks!"
bash will write this text to the screen when it reaches that line in your script.

Variables

Like any programming language bash uses variables to store data in. Variables are pieces of computer memory that have a name and contain one or multiple values. You create a variable using =
name="what?"
Now a piece of memory in my computer is reserved for storing the value “what?” and that piece is called name. This is called an assignment: you assign a value to a variable. You can create variables in your script or you can create them on the command line. They will be alive until you close the terminal.

To use this name in your script you can refer to this piece of memory by appending $ to the variable name:
echo "Hi, my name is," $name
This line of code will write “Hi, my name is, what?” to the screen.

If you reassign the variable, the value “what?” is removed and forgotten and the new value will be used if you refer to the variable:

1 – Practice a bit more on your own computer:
Open Replit, create a bash script and run it.