Shell Programming
Shell Programming
The UNIX shell program interprets user commands, which are either directly entered
by the user, or which can be read from a file called the shell script or shell program.
Shell scripts are interpreted, not compiled. The shell reads commands from the script
line by line and searches for those commands on the system.
Shell script
Shell script is a file-containing list of commands to be executed in a particular order.
A good shell script will have comments, (a statement preceded by a pound sign, #) ,
describing the purpose of the statement.
In a script we can use conditional tests, such as value A is greater than value B, loops
or iterative statements to execute some steps repetitively or to navigate through a list
of data or records and do processing. We can use files to read and store data. Can use
variables to read and store data. A script may include functions also.
When a script is executed, the shell reads the commands one by one and executes
them .
We can create the simple shell script file by using vi editor or cat command like,
$ vi test.sh
$ cat > test.sh
Below mentioned shebang statement should be the first statement in the shell script as
it tells the system that the commands mentioned in the shell script are to be executed
by the shell /bin/sh
#!/bin/sh
Consider the shell script with just two commands pwd & ls.
$cat test.sh
#!/bin/bash
pwd
ls
●
● Automation of repetitive task
●
●
● Creating our own power tools/utilities.
●
●
● Automating command input or entry.
●
●
● Customizing administrative tasks.
●
●
● Creating simple applications.
●
●
● Automating administration tasks such as adding new users, removing obsolete
users etc
●
●
● Monitoring your Linux system.
●
●
● Data backup and creating snapshots.
●
●
● Dumping Oracle or MySQL database for backup.
●
●
● Creating email based alert system.
●
●
● Find out what processes are eating up your system resources.
●
●
● Find out available and free memory.
●
●
● Find out all logged in users and what they are doing.
●
●
● Find out if all necessary network services are running or not. For example if
web server failed then send an alert to system administrator via a pager or an
email.
●
●
● Find out all failed login attemp. If login attempt are continued repeatedly from
same network IP, automatically block all those IPs accessing your
network/service via firewall.
●
●
● User administration as per your own security policies.
●
●
● Find out information about local or remote servers.
●
●
● Configure server such as BIND (DNS server) to add zone entries.
●
●
● Arithmetic Operators.
●
●
● Relational Operators.
●
●
● Boolean Operators.
●
●
● String Operators.
●
●
● File Test Operators.
●
●
● There must be spaces between operators and expressions for example 2+2 is
not correct, where as it should be written as 2 + 2.
●
●
● Complete expression should be enclosed between ``, called inverted commas to
execute expr command correctly.
●
Arithmetic Operators
It is very important to note here that all the conditional expressions would be put
inside square braces with one spaces around them, for example [ $a == $b ] is correct
where as [$a==$b] is incorrect.
Relational Operators
Below are relational operators which are specific to numeric values. These operators
would not work for string values unless their value is numeric.
For example, following operators would work to check a relation between 10 and 20
as well as in between "10" and "20" but not in between "ten" and "twenty".
Assume variable a holds 10 and variable b holds 20 then:
Description Example
Operator
Check if the value of left operand is less than the [ $a -lt $b ] is true
value of right operand, if yes then condition
-lt
becomes true.
Check if the value of left operand is greater than [ $a -ge $b ] is false
or equal to the value of right operand, if yes then
-ge
condition becomes true.
It is very important to note here that all the conditional expressions would be put
inside square braces with one spaces around them, for example [ $a <= $b ] is correct
where as [$a <= $b] is incorrect.
Boolean Operators
Assume variable a holds 10 and variable b holds 20 then
Description Example
Operator
String Operators
These are string operators. Assume variable a holds "abc" and variable b holds "efg"
then:
Description Example
Operator
Check if the str is not the empty string. If [ $a ] will return true
it is empty then it returns false.
str
Description Example
Operator
-d file
-r file
-w file
Returns true, Check if file is execute [ -x $file ] is true.
-x file
-e file
Meaning Examples
Wild
card
/Shortha
nd
Matches any string or group will show all files
of characters.
* $ ls *
Description
Quote
\$
\'
\"
\\
Any character immediately following the backslash loses its
Backslash special meaning.
●
● $ for parameter substitution.
●
●
● Backquotes for command substitution.
●
●
● \$ to enable literal dollar signs.
●
●
● \` to enable literal backquotes.
●
●
● \" to enable embedded double quotes.
●
●
● \\ to enable embedded backslashes.
●
●
● All other \ characters are literal (not special).
●
If..else statements
We can use “if..else” statement which can be used as decision making statement to
select an option from a given set of options.
Unix Shell supports following forms of if..else statement:
● if...fi statement
● if...else...fi statement
● if...elif...else...fi statement
Syntax:
● if...fi statement
if [condition]
then
command(s)
fi
● if...else...fi statement
if [ condition(s) ] then
command(s)
else
command(s)
fi
● if...elif...else...fi statement
if [ condition(s) ]
then
command(s)
elif [ condition(s) ] # Many elif-then allowed
then
command(s)
else
command(s)
fi
test command in if condition
We can use test command as condition of if condition as used in the below script.
$cat if_test.sh
#!/bin/sh
echo “Do you want to quit (Y/y)? ”
read ans
if test $ans ==’y’ –o $ans==’Y’
then
exit
else
echo “ to exit enter N or n”
fi
case...esac Statement
We can use multiple if...elif statements to perform a multiway branch. However, this
is not always the best solution, especially when all of the branches depend on the
value of a single variable.
Unix Shell supports case...esac statement which handles exactly this situation, and it
does so more efficiently than repeated if...elif statements.
The interpreter checks each case against the value of the expression until it finds a
match. If nothing matches, goes with the default condition.
Syntax:
;;
pattern2)
;;
pattern3)
;;
esac
Here string word is compared against every pattern until a match is found and the
statement(s) following the match pattern executes. If shell cannot find any match, the
case statement exits without performing any action. When statement(s) part is
executed. The command ;; indicates program flow should jump to the end of the
entire case statement.
There is no maximum number of patterns, but the minimum is one.
Example:
#!/bin/sh
COURSE=”DB”
case “$COURSE” in
“Java”) echo “Java is a programming language”
;;
“Perl”)echo “Perl is scripting language”
;;
“DB”)echo “Oracle is a DB”
;;
esac
Output:
Oracle is a DB
Iterative Statements/Loop :
Loops are a powerful programming tool that enables you to execute a set of
commands repeatedly.
● while loop
● for loop
● until loop
while loop
Here condition is evaluated by shell at the beginning of each iteration. If the resulting
value is true, given command(s) are executed. If condition is false then no command
would be executed and program would jump to the next line after done statement.
Syntax:
while condition
do # executed as long as the condition is true
command(s)
done
Example:
a=0
while [ $a -lt 3 ]
do
echo $a
a=`expr $a + 1`
done
Output:
0
1
2
until loop
Here condition is evaluated by shell. If the resulting value is false, given command(s)
are executed. If condition is true then no command would be executed and program
would jump to the next line after done statement.
Syntax:
until condition # complement of while
do
# executes the body as long as the condition is false
command(s)
done
Example:
a=0
until [ ! $a -lt 3 ] do
echo $a a=`expr $a + 1`
done
Output:
0
1
2
for loop
For loop operate on lists of items. It repeats a set of commands for every item in a list.
Syntax:
for var in w1 w2 w3.. wn
do
command #Statement(s) to be executed for every w in the list
done
Example:
for var in 0 1 2 3 4 5
do
echo $var
done
Output:
0
1
2
3
4
5
Example:
do
cat ${filename}
done
String Handling
The expr is quite handy for finding the length of a string and extracting a sub-string:
Length of the string:
$ str=”abcdefghijk” ;
$ echo $n
11
expr gave how many times any character (.*) occurs. This feature is very useful in
validating data entry.
Extracting a sub-string:
$ str=”abcdefghijk” ;
gh
$ str="abcdefghijk"
$ expr "$str" : '...∗
'
cdefghijk
$ str=”abcdefghijk” ;
1.
2.
3.
1.
2. Command Line Arguments
3.
To make a shell script a generalized script, we should avoid hard coding. User should
be able to provide the values required for processing as input while running the shell
script. To facilitate this we have to use command line arguments.
The statement we write in the command prompt starting with the command followed
by list of arguments is the command line argument.
Example:
$ ls dir1 dir2 dir3
A set of shell variables are there to represent the command line arguments.
$0 – represents the command name (first word on command line). For above example
“ls”
$1 - the first argument of command (second word/symbol ).For the above example
dir1
$2 – the second argument to the command. For the above example, dir2
In this way we can use up to $9
The command-line arguments $1, $2, $3...$9 are also called positional parameters,
with $0 pointing to the actual command/program/shell script and $1, $2, $3, ...$9 as
the arguments to the command.
Consider below sample shell script “test.sh”
$cat test.sh
#!/bin/sh
Let’s execute the above shell script “test.sh”. Remember to change File access
permission of script to execute
$ sh test.sh arg1 arg2 arg3
Program name is test
First argument is arg1
Second argument is arg2
Number of arguments passed = 3
The arguments are arg1 arg2 arg3
There’s another way to execute the script using ./
$ ./test.sh arg1 arg2 arg3
Program name is test
First argument is arg1
Second argument is arg2
Number of arguments passed = 3
The arguments are arg1 arg2 arg3
Example: read.sh
#!/bin/sh
Note that “-n” given to the echo command causes it to keep the cursor on the same
line; i.e., it does not output a carriage return at the end of the prompt.
Next, we invoke the read command with “text” as its argument. What this does is wait
for the user ro type something followed by a carriage return (the Enter key) and then
assign whatever was typed to the variable text.
Execution:
$sh read.sh
Enter some text > This is some text
You entered: This is some text
Validation of Command Line Arguments
Let us assume, we have one shell script which requires exactly 2 arguments to
execute. Shell script should throw proper error message in case user has not given
exactly two arguments.
Let us have a small shell script "test.sh" to show how to implement validations.
#!/bin/sh
if [ $# -ne 2 ]
then
else
$ ./test.sh
Not sufficient arguments, please give exact 2 arguments
$ sh test.sh abc
Not sufficient arguments, please give exact 2 arguments