Just like all the commands we've used so far, we can create our own bash scripts that we can store and execute, without having to type all the commands again. This is especially useful when moving into automation and repetitive tasks or to store commands that are very long and tedious to type or remember. There are only three steps needed to create our first bash script:
Let's start with the first two steps, so all that's left to do, is write our actual script. The first line simply puts the three-word echo hello world
in our
file called script.sh
, just like we've done before. The second line sets user permissions to allow the user +u
to execute +x
the file as a script.
Now the above would in most cases already be enough and we just wrote our first tiny bash script that we can execute by calling ./script.sh
. However, to tell the CLI that
it should be interpreted as a bash script, it's common practice (read necessary) to add a so-called shebang to the top of the file. Depending on the shebang, we
can even tell the terminal to interpret the file in a different language, such as JavaScript or PHP, and write our executable in that language!
Now what's left to do is write the actual content of our script. Just like other languages, bash (and therefore the CLI) has various primitives, loops, and conditions that we'll take a closer look at in the following chapter.