The makings of a shell script

Knowing how to work with the base OS that you run your work on has numerous benefit. Any serious developer that has been doing real work has undoubtedly come accross command line utilities on more than an occasion or two. Being able to write a shell script aka a bash script is a skill that will serve you immensely in your work. So without further ado let's dig in!

The anatomy of a shell script:

Bash scripts have the extension ".sh" . If you are in the terminal cd to a directory of your choice and make a test script by typing


Every shell script should begin with the she-bang line. That wording comes from the fact its a combination of the hash # and the bang (aka exclamation) character !. So lets open up your script and put one in. It looks a little something like this:

#!/usr/bin/env bash

Open your script by typing vim and then press i to enter input mode and type your line.

The above line tells the system to execute the file in the bash shell, bc there are other binaries that could be executed from the command line and other shells.

Once you have this specified you can fill the body of your script out with any bash valid syntax. Let's see what some of that looks like.

Common Bash syntax

To send info to the cli you echo something out:

echo "What is your name?"

Reading input from a question in the console can by done like this:

read name

#And you access it like so:
echo $name

A conditional is presented like so:

#Note the spaces near the braces and the semicolon.
if [ 'someVal' = 'someVal' ]; then
   echo 'Hey it matches'
#also note the conditional ends with the peculiar fi

Last Step: Make it run!

There are of course plenty of other things you can do and I will cover in future additions to this article or perhaps other articles. This should get you started though. Before we call it a night though there is one other thing you have to do: Make your bash script executable:

sudo chmod +x

See ya next time!