Shell Programming - Introduction


This is an introduction to Shell Programming tutorial.

Unix command

These are the commands that we execute by typing in the shell prompt.

Example: The cal command will print the calendar and will show us the current month.


What is a Shell Program?

In simple terms a Shell Program is a series of Unix commands written to perform some task.

Shell Program is also referred as Shell Script.

Creating a Shell Script file

Open the terminal and using the vi or vim command create a file and give it any name of your choice and save it with the extension .sh.

Example: In the following example we are creating a file using the vi command.


YUSUF-MBP:example yusufshakeel$ ls -la
total 8
drwxr-xr-x  3 yusufshakeel  staff   96 Dec 29 09:10 .
drwxr-xr-x@ 5 yusufshakeel  staff  160 Dec 29 09:10 ..
-rw-r--r--  1 yusufshakeel  staff   19 Dec 29 09:09

Shebang line

The first line of a shell script file is called the Shebang line and it contains the absolute path of the Bash interpreter.


The shebang line given above instructs the program loader to run the interpreter /bin/sh and pass the content of the shell script file as the first argument.

Types of shebang lines

Some of the commonly seen Shebang lines that we will encounter are given below.

  • #!/bin/sh This will use Bourne Shell or a compatible shell of the system.
  • #!/bin/bash This will use Bash Shell.

Hello World

Lets start our journey by printing "Hello World" using a Shell Script.

Open the file using the vi command.

Once the file opens press the i key to enter into INSERT mode to start typing some code.

Now write the following code inside the file.

echo "Hello World"

In the above code we are using the echo command to print the string "Hello World".

Now press the Esc key to come out of the INSERT mode. Then type :wq keys to save the file and exit.

Awesome! We have successfully created our first shell script file. Now lets go ahead and execute the script.

Execute shell script file

To execute a shell script file we type the sh filename command in the terminal.

So, to execute the script file we will type the following command in the terminal.



YUSUF-MBP:example yusufshakeel$ sh 
Hello World

If you are unable to execute the shell script then you can make it executable using the chmod command.

In the following example we are making the file executable.

$ chmod +x

When to use Shell Scripts?

We use shell script when we want to automate our tasks. For example, we can create a shell script and setup a cron job to remove temporary files from the server that are older than 7 days.