Creating and running bash scripts

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:

  • Create a file and make sure it's executable
  • Tell the CLI the file is a bash script and should be interpreted as such
  • The actual content of our script that will be executed

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.

command line
echo "echo hello world" > script.sh
chmod u+x script.sh

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!

command line
#!/usr/bin/env bash # bash
#!/usr/bin/env node # node
#!/usr/bin/env php # php

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.