Shell Programming - Introduction

Unix

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.

Output:

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 helloworld.sh file using the vi command.

vi helloworld.sh


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 helloworld.sh

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.

#!/bin/sh

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 helloworld.sh 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.

#!/bin/sh
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 helloworld.sh script file we will type the following command in the terminal.

sh helloworld.sh

Output:

YUSUF-MBP:example yusufshakeel$ sh helloworld.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 helloworld.sh file executable.

$ chmod +x helloworld.sh

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.