Official website for Linux User & Developer
FOLLOW US ON:
Aug
13

Shell scripting for system administrators: the basics

by Swayam Prakasha

For system administrators shell scripting can be a very useful way to drastically improve workflow. Join Swayam Prakasha to find out how you can employ some fundemental tips and techniques to make your life easier…

Control constructs
One can use four main constructs inside a shell script for flow control. They are:
1. if…then…elif…else
2. do…while
3. for
4. case

Let us consider another script to discover more on this:

#!/bin/sh

if [ “$1” = “1” ]
then
 echo “Your first choice is good”
elif [ “$1” = “2” ]
then
 echo “Your second choice is also good”
elif [ “$1” = “3” ]
then
 echo “Your third choice is neat”
else
 echo “How come you are silent?”
fi

As can be seen, based on the command line parameter that we are passing (while executing the script), different parts of the shell script will get executed. Passing arguments to a shell script is very helpful in many situations. The screenshot ‘Figure 4‘ gives the output of executing the above script with different input parameters.

Lets understand the case construct with an example:

!#/bin/sh
case $1
in
1) echo ‘Passed in first class’;;
2) echo ‘Passed in second class’;;
*) echo ‘Retake the test’;;
esac

In the above example, the input parameter is compared with a specific pattern and if a match is found, then the body of the corresponding pattern is executed. We also have a default case that will get executed if our input parameter is different from the two specified patterns. The screenshot ‘Figure 5‘ explains the execution of the above script.

twitter follow us
Pages: 1 2 3 4 5 6
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.