Get startedGet started for free

Your first Bash script

1. Your first Bash script

In this lesson, you will move beyond command line execution and create your first Bash script.

2. Bash script anatomy

There are several key parts to a Bash script. The first line has a shebang or hash-bang then the path to where Bash is. Most commonly that is slash usr slash bash. Bash could be in a different location so you can check where Bash is using the command 'which bash'. The middle of the script contains your code. It may be simple commands or more advanced code you will learn in this course.

3. Bash script anatomy

Once your script is written you can save it and run it. The file extension is usually dot s h. Though this is only convention if you have the first line with the she-bang and path to Bash mentioned before. You can run using the command Bash followed by the script name. If the first line in your script is the she-bang and path to Bash you can also simply run as dot slash and the script name.

4. Bash script example

Here is an example of a full script. It begins with the she-bang and path to Bash. There are a few simple lines of code. If you saved it as eg dot s h then you could run using dot slash e g dot s h. The output is produced here, each code line is run in turn.

5. Bash and shell commands

Each line of a Bash script can be a shell command. So, you can also use pipes to create a chain of terminal commands in the shell. Something you are perhaps already familiar with. Here is a text file called animals dot txt. It contains some animals and their grouping. We want to determine how many animals are in each group.

6. Bash and shell commands

You may be able to write a chain of commands piped into each other in the terminal. However, let's instead put this into a script. The script begins with the hash-bang as we know. Then instead of a simple echo command like the last example, we add in the command we would use. This command concatenates the text file, pipes that to the cut command which will split on spaces and take the second field (the animal group). The chain then sorts and does a unique count. You could try this in your own terminal to confirm it works there. Now instead of copying and pasting in that chain each time you can simply run Bash group dot sh. You will get the aggregates returned!

7. Let's practice!

Let's practice writing your first simple Bash scripts!