Bash is a Unix shell, which is a command-line interpreter. It’s only job is to run commands given by the user. If you have ever used a terminal for something on a Linux based system, you probably have already used it without knowing. As well as being used as a shell for most Linux systems, it can be used to create and run scripts. This is what this tutorial will talk about.
- Device with bash installed
Before making your first script you will need to know how to make a valid script file.
This is quite simple as a bash script is just a text file, most script writers like to use the extension .sh or .bash, however that is not required.
In this tutorial I will create a bash script file using:
touch my-script. This will simply create a empty text file.
To execute a bash script we can use:
bash ./my-script. This however requires you to know that the file is written to be run with bash, we can change that by using a shebang.
A shebang will allow us to indicate what program to run the file in; a shebang is simply a couple of characters at the start of the file, these characters are:
#!; followed by the executable path to run.
Let’s now look at two possible ways we could indicate our file should be run with bash.
This first method points to the bash executable directly.
This version uses “env” which uses the first bash executable on a users $PATH. This has the added benefit of controlling which bash executable to run, on most systems it will have the same effect as running the previous example.
Now after using a shebang we can run a script using:
./my-script instead. This however will require you on most systems to mark the script executable. You most likely will do this by running the following command:
chmod +x my-script.
Let’s now create a basic script. While it will not be a useful script it will allow you to understand how to start scripting with bash.
As you can see we are using the “echo” command which is a program that will output to stdout the parameters you provide. If you run this you should see “Hello World” output.
Notice how I said that “echo” is a program. Well bash does not have many built in features unlike Python which has the “print” function. This is what separates scripting and programming.
This tutorial is aimed to provide you the bare minimum on creating a bash script.
Reading my other tutorials will allow you to learn more about bash scripting: here.