Linux Topic
   >  Shell Scripts
   >  Using Comments
   >  Passing Arguments to Scripts
   >  Using Conditional Statements
   >  Using Loop Statements
   >  Reading and Writing Files
   >  Script Permissions
   >  Cron and Scheduling
   >  A Scripting Example
   >  Other Scripting Languages

 

Conditional Processing in Shell Scripts

Conditional Structures

All programming languages include at least one construct for dealing with decisions. Shell scripting is no exception - the main one being if..then..else. Virtually every computer language in the world has this construct, so chances are that it will be familiar to you. It consists of three parts:

  • The condition clause, which defines what the test is which decides the path of the code
  • The then clause, which defines what code will execute if the condition is true. This can span multiple lines
  • The else clause, which defines what code will execute if the condition is false. This can also span multiple lines

Consider the following code snippet:

if [ $1 == 'fred' ]; then
   echo "Hello Fred!"
else
   echo "Hello!"
fi

What this states is that either of two statements (echo "Hello Fred!" or echo "Hello!") will be executed (-but not both), depending on the outcome of the test ($1 == 'fred'). Notice that the condition itself is surrounded by square brackets. If $1 equals the string "fred", then echo "Hello Fred!" will be executed. If not, then echo "Hello!" will be printed. If we run the script, supplying different parameters on the command line, you can see the effect it has on the code:

$ ./myScript.sh fred
Hello Fred!
$ ./myScript.sh burt
Hello!

Note that we could have specified multiple lines of code in the then and else clauses if we wanted: any statements between the "then" and the "else" keywords will be executed if the statement is true; everything between the "else" and the "fi" keyword will be executed if the condition is false:

if [ $1 == 'fred' ]; then
   echo "Hello Fred!"
   echo "How are you today?"
   myVar=0
else
   echo "Hello!"
   echo "I don't believe we've been introduced..?"
   myVar=1
fi

echo "myVar is $myVar"

The new output should look as follows:

$ ./myScript.sh fred
Hello Fred!
How are you today?
myVar is 0
$ ./myScript.sh burt
Hello!
I don't believe we've been introduced..?
myVar is 1

Note: the echo "myVar is $myVar" command executed for both invocations because it was outside of the conditional statement (-i.e. after the ending fi)


HomeSite IndexDesktop GuideServer GuideHints and TipsHardware CornerVideo SectionContact Us

 sitelock verified Firefox Download Button