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
-
#!/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
-
#!/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:
-
#!/bin/sh
-
MESSAGE="Hello Unix"
Shell Script Body
The body of the script follows after the declaration section.
-
#!/bin/sh
-
MESSAGE=“Hello Unix”
-
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.
-
#!/bin/sh
-
MESSAGE=“Hello Unix”
-
# This is a comment
-
echo $MESSAGE # This is a comment
Steps to Run the Script above
- 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.
- In Unix command line, type chmod 755 and hit Enter. This command will make you script executable.
- 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.
-
#!/bin/sh
-
MESSAGE=“Hello Unix”
-
# This is a comment
-
echo $MESSAGE # This is a comment




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