Saturday, July 25, 2009

Starting with Shell Script

What is a Shell Script?

A shell script is a text file that is interpreted as a series of commands executed one after the other to achieve the desired result. It can cater for interactivity and complexity where decisions are required on certain conditions.

Here is an example of what a shell script looks like

#!/bin/bash
#
# Prog: Sample Shell Script, outputs Hello World
# Author : Jayant C Varma
#
echo "Hello World"

What does it all mean?
The first line indicates to the kernel that this is a script. So every script should start with the first line being #!/bin/bash , now if one was to use python or perl as the scripting language instead of bash, then the line would correspondingly change to #!/usr/bin/python or #!/bin/perl , The path that folows the #! is the path to where the interpreter lies, so if you have a custom language that you might want to use, you can specify the path to the interpreter and it would work.

The # is a comment, and it is a good idea to document and write on the top after the first line about the author and the function of the program.

The main guts of the program that outputs the data is the line echo "Hello World" that prints to the terminal the words Hello World.

Is that all that is required to make a script?
Yes, that is all that is required to make a script. Running the file on its own will not work as it is just a text file. So to run it we can use the command line

$ > bash myscript.sh

this shall run the script caled myscript.sh

To make the script run on its own, we need to midify the file from being an ordinary file to an executable file, we do so by changing the file permissions using the command chmod.

$ > chmod +x myscript.sh

Now the myscript.sh file is no longer an odinary text file, but an executable script file
to run the same, we can simply type, at the command line

$ > ./myscript.sh

We shall see in other posts why do we use the ./ before the filename instead of just typing the myscript.sh, an exercise for you, try it out and see what happens if you do not include the ./

Shell Scripting

One of the advantages of Linux/UNIX is that it was not build as a GUI based Operating System. It was a System Administrators OS that was text based (Terminal based) and multi-tasking. Catering for every utility that might be used for system administration would be difficult. A text based scripting language was developed. This is a very powerful and can allow for a multitude of complex operations, right from setting permissions to performing interactive installations.

To extend the capabilities of the scripting language, two additional utilities were developed called AWK and SED. They are quite useful and complex and deserve a book on themselves.