Unix Shell Script Structure

September 15, 2007 by Mark Marucot 

The shell script structure consists of header, declaration and body. These three sections are basic structure of shell script. But script can run with header and body section only. Declaration section is useful for reading and passing values within the script.

Shell Script Header

Shell script conventionally starts with shell script header which define which shell should be used in running the script. This can be either under sh shell or bash shell. It means that even if you are using csh, ksh, or anything else as your interactive shell, that what follows should be interpreted by the Bourne shell.
Similarly, a Perl script may start with the line #!/usr/bin/perl to tell your interactive shell that the program which follows should be executed by perl. For Bourne shell programming, we shall stick to #!/bin/sh.

Sh Shell Script Header

CODE:
  1. #!/bin/sh

This means that the shell script should be run in the sh shell regardless of which shell the user has chosen.
Bash Shell Script Header

CODE:
  1. #!/bin/bash

This means that the shell script should be run in the bash shell regardless of which shell the user has chosen.

Shell Script Declaration

Declaration section follows after the header section. See line 2 below:

CODE:
  1. #!/bin/sh
  2. MESSAGE="Hello Unix"

Shell Script Body

The body of the script follows after the declaration section.

CODE:
  1. #!/bin/sh
  2. MESSAGE=“Hello Unix”
  3. echo $MESSAGE

My First Script

Combining all the sections, from header, declaration and body. We now have our first script. Copy and paste the code below to you text editor. Save it to myfirstscript.sh or to any filename you like as long as it has .sh extension.

CODE:
  1. #!/bin/sh
  2. MESSAGE=“Hello Unix”
  3. # This is a comment
  4. echo $MESSAGE # This is a comment

Steps to Run the Script above

  1. Copy and paste the code below to you text editor.
  2. Save it to myfirstscript.sh or to any filename you like as long as it has .sh extension.
  3. In Unix command line, type chmod 755 and hit Enter. This command will make you script executable.
  4. myfirstscript.sh and hit the Enter key. Just change the filename if you used a different filename

Commenting

The line 3 below begins with a special symbol #. This marks as a comment and ignored by the shell. The only exception is in the first line which starts with #! which define which shell should be use in running the script.

CODE:
  1. #!/bin/sh
  2. MESSAGE=“Hello Unix”
  3. # This is a comment
  4. echo $MESSAGE # This is a comment

Related Posts

Comments

Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!