Network Security Library
Javascript Feeds    RSS Feed    Security Dashboard    SearchSecurity.com
About | Contact | Advertise | Site Map
Print Printer Friendly      PDF PDF Version
intrusion detection E-mail      Save Save This

Shell Script Programming


{LANG_NAVORIGIN} Operating System Linux
Colin Sauze 07/02/2005



Anatomy of a shell script



There is only one thing you must have in a shell script and that's a line specifying what interpreter is to be used to interpret this script. This begins with the symbols #! and is followed by the full path to the interpreter, this will usually be “/bin/bash” for bash scripts and “/bin/sh” for bourne shell scripts. Some system administrators may install bash elsewhere (“/usr/local/bin” is common) you can find out where by typing “which bash”. So basically the first line of the script should be “#!/bin/bash”. In order to run the script you must first give it execute permissions, this is done by typing “chmod u+x scriptname”, you only need to do this once per script. You can now run the script by typing “./scriptname” if your current directory is that of the script or by specifying the scripts path, for example if the script is in “/home/fred” and is called “myscript” then type “/home/fred/myscript”. An alternate way to run scripts is to run the interpreter executable (e.g. “/bin/bash”) and give the script name as an argument, e.g. “/bin/bash” “/home/fred/myscript”, if you do this you don't need to do the chmod.

So the simplest script you can have:
#!/bin/bash
Running the script:
chmod u+x myscript
./myscript

The hello world script


There is a tradition in programming that the first program you should write for any language should be one which says “hello world” on the screen, so in keeping with that tradition here is how to do it in with bash scripts. The echo command simple writes output to standard out (usually the users' console).
#!/bin/bash
echo “hello world”

Comments:


Any line beginning with a # (except the #! line) is what is known as a comment and is for you to write little reminders to yourself (or anyone else who will read the code) about what the code does. This can be very helpful when you write a complex program, leave it for a while and then come back to it only to find you haven't a clue what something does or why you did it! Comments can also be useful to leave information about how to run a program, who wrote it and their contact details.

Script variables


All programming languages feature the concept of variables. Variables are a name to which you can assign values, they are best likened to the way you use letters in algebra where you might say x=5.y=2x (so y=10). Unlike some languages there is only 1 type of variable in bash which can hold anything you like including letters, spaces, numbers, punctuation and anything else. In order to create a new variable you just specify the variable name followed by = and its value (many other programming languages require you to declare that a variable exists before you can use it). When you assign/create a variable you simply write “variablename = value”, if the value contains a space enclose the whole thing in “ for example variable = “hello world”. Whenever you want to reference a variable you must place a $ symbol in front of its name. It is convention (but not required) to put variable names in upper case.

Assigning a variables value example:
#!/bin/bash

VARIABLE = “value”

VARIABLE2 = $VARIABLE

echo $VARIABLE2
Here $VARIABLE is assigned the value "hello", and $VARIABLE2 is then assigned whatever $VARIABLE is, so it too becomes "hello". When the echo command is called it will display the value of $VARIABLE2.

There are several special variables in a script, these are used to do things like tell you how many arguments the script was given when it was started, the status of the last command and the arguments to the script. The table below explains these in more detail.

Variable namepurpose
$1, $2....$9These variables hold the values of the arguments given to the script. If I have a script called myscript and I start it by typing “./myscript.sh a b” then $1 will be “a” and $2 “b”.
$#This tells variable tells you how many command line arguments there are so, this is useful to help work out if the user has specified the correct options to your script.
$?This variable gives what is known as the return code for the last command executed. All programs return a value when they run, typically they return 0 if what they did succeeded and something other than 0 if they fail each program has its own meanings for these.


You can assign a variable the output of a programs standard output by using backticks (` symbols) around the programs name. For example we can get the current working directory by setting a variable to the output of the pwd program:
#!/bin/bash
DIR=`pwd`
echo “Working directory is $DIR”
This will output the name of our working directory when we started the script, so if we were in /home/fred when we started it will say “Working directory is /home/fred”.

You can also do this with all the other statements described in the rest of this tutorial instead of using variables or giving exact values.


If and case statements.



The need often arises to compare two (or more) variables or to test to see if the value of a variable is equal to something. For this there are 2 statements in shell scripts which help us, these are “if” and “case”. If is used we want to compare a variable to a small number of different values or other variables (like 1 or 2), case is used for comparisons with far more possible outcomes.

An if statement is very simple to construct you simple write, “if [ “$VARIABLE” = “$VARIABLE2” ]” or “if [ “$VARIABLE” = “value” ]”. You MUST place the name of the variables and the values in double quotes (“) and you must leave a space between the if and the [. Some implementations of the bourne shell also require a space between all the other elements, bash does not but it helps to make things a bit more readable if you do, as a general rule shell scripts are very strict about spaces. An if statement must be proceeded by a then statement, followed by whatever action you take if this condition is true, this code can span multiple lines and it is common practice to indent it by pressing tab at the beginning of each line. To end the if statement you must put “fi”. Here's an example:
#!/bin/bash
If [ “$1” = “hello” ] 
then
    echo “you specified hello as an argument to this script”
fi
Sometimes we also want to have some code which handles what to do if the condition doesn't evaluate to true. This is done by writing else instead of fi at the end of the code for the condition being true. Instead of writing then on a separate line it can be written after a ; on the same line as the if, a ; means the same as a new line as far as the shell script is concerned, you can actually type multiple commands this way at the command line. For example:
#!/bin/bash
if [ “$1” = “hello” ] ; then
    echo “you specified hello as an argument to this script”
else
    echo “you didn't specify hello as an argument to this script”
fi
Sometimes we don't want to test if two things are equal but want to test for inequality, this is done by putting != instead of = in the if statement. If can also compare numbers to see if one number is less than the other, greater than the other etc. The following table describes how:

SymbolMeaning
-geFirst value is greater than or equal to the second
-gtFirst value is greater than the second
-leFirst value is less than or equal to the second
-ltFirst value is less than the second


Example code:
#!/bin/sh
A=”1”
B=”2”
if [ “$A” -lt “$B” ] ; then
    echo A is less than B
fi
Sometimes we need to check more than one thing in an if statement, we can either specify that every statement must evaluate to true or we can specify that one of them does. To specify that one statement and another evaluate to true we use a “-a” between each, to show that one or another is true we use a “-o”. Its also possible to place an if statement within an if statement, this is known as a nested if statement. The following example shows two conditions being checked to make sure both are true and then another is checked as a nested if with an alternative provided if it isn't true.
#!/bin/sh
A=$1
B=”2”
if [ “$A” -lt “$B” -a “$A” = “1” ] ; then
    if [ “$B” = “2” ] ; then
        echo “A is less than B, and A is 1. B is also 2”
    else
        echo “A is less than B, and A is 1. B is not 2”
    fi
fi
When we want to compare a variable to a lot of other values writing a whole series of if statements can become very tedious, so we can use a case statement instead. This works by specifying which variable we want to test and the providing different cases for each value it could take, we can also provide a default case for any value we don't specify. This is done by writing “case $VARIABLENAME in”. We then start each case with its value followed by a ). Each case is ended by writing ;; on its own line. The default case is specified with a *). The whole statement is ended by writing esac (like if is ended by writing fi).
#!/bin/bash
A=”1”
Case in $A
    1)
         echo “A is 1”
         ;;
    2)
        echo “A is 2”
        ;;
     *)
        echo “A is not 1 or 2”
        ;;
esac 















E-Mail Link

Your IP address will be sent with this e-mail
From e-mail to e-mail



35289 Views
4.25/5 Rating
8 Votes
Newest
Highest Rated
Most Viewed
Reference

Javascript Feeds
RSS (New Papers)
Security Dashboard

About SecurityDocs
Advertise
Contact

Valid HTML 4.01!
Valid CSS!


Unless otherwise noted, all paper copyrights are owned by the author. The rest copyright 2003-2005 TechTarget

Privacy : Contact