Shell Programming Study Material1
Shell Programming Study Material1
Shell Programming Study Material1
A shell is a program that acts as the interface between you and the Linux system, enabling you to
enter commands for the operating system to execute. In that respect, it resembles the Windows
command prompt, but as mentioned earlier, Linux shells are much more powerful.
On Linux, the standard shell that is always installed as /bin/sh is called bash (the GNU Bourne-
Again Shell), from the GNU suite of tools.
You can check the version of bash you have with the following command:
$ /bin/bash –version
Many other shells are available, either free or commercially. The following table offers a brief
summary of some of the more common shells available:
myvar=”Hi there”
echo $myvar
echo “$myvar”
echo ‘$myvar’
echo \$myvar
echo Enter some text
read myvar
echo ‘$myvar’ now equals $myvar
exit 0
Making a Script Executable
Now that you have your script file, you can run it in two ways. The simpler way is to invoke the
shell with the name of the script file as a parameter:
$ /bin/sh first
Or
$ chmod +x first
Then $ first
Environment Variables
Control Structures
if
The if statement is very simple: It tests the result of a command and then conditionally executes
a
group of statements:
if condition
then
statements
else
statements
fi
Sample programme: test3.sh
echo “Is it morning? Please answer yes or no”
read timeofday
if [ $timeofday = “yes” ]; then
echo “Good morning”
else
echo “Good afternoon”
fi
exit 0
elif
Unfortunately, there are several problems with this very simple script. For one thing, it will take
any answer except yes as meaning no. You can prevent this by using the elif construct, which
allows you to add a second condition to be checked when the else portion of the if is executed.
You can modify the previous script so that it reports an error message if the user types in
anything other than yes or no. Do this by replacing the else with elif and then adding another
condition:
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
if [ $timeofday = “yes” ]
then
echo “Good morning”
elif [ $timeofday = “no” ]; then
echo “Good afternoon”
else
echo “Sorry, $timeofday not recognized. Enter yes or no”
exit 1
fi
exit 0
Assignment9:
Write a shell script to print the following number pattern (using nested for loop).
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Assignment10:
Write a shell script to print the prime numbers between n & m. [n & m are user input] (using nested
while loop).
Reference:
Beginning Linux Programming by NEIL MATTHEW published by SPD