Shell scripting for system administrators: the basics

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:
[sourcecode language=”bash”]#!/bin/sh

if [ “$1” = “1” ]
echo “Your first choice is good”
elif [ “$1” = “2” ]
echo “Your second choice is also good”
elif [ “$1” = “3” ]
echo “Your third choice is neat”
echo “How come you are silent?”
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:
[sourcecode language=”bash”]!#/bin/sh
case $1
1) echo ‘Passed in first class’;;
2) echo ‘Passed in second class’;;
*) echo ‘Retake the test’;;
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 username=”linuxusermag”]