Shell Scripting
Shell Scripting
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.
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
#!/bin/sh
Consider the shell script with just two commands pwd & ls.
$cat test.sh
#!/bin/bash
pwd
ls
Importance of shell script
Shell scripts are basically used for automating processes that we repeat at the
prompt .
$ sh filename
Or
$ ./filename
In this case we have to modify the file access permissions of the shell script before
execution.
Arithmetic Operators.
Relational Operators.
Boolean Operators.
String Operators.
Example:
#!/bin/sh
val=`expr 2 + 2`
Output:
$ Total value : 4
There must be spaces between operators and expressions for example 2+2 is
not correct, where as it should be written as 2 + 2.
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".
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
String Operators
These are string operators. Assume variable a holds "abc" and variable b holds
"efg" then:
Assume a variable file holds an existing file name "test" whose size is 100 bytes
and has read, write and execute permission on:
Wild
card Meaning Examples
/Shorthand
Matches any $ ls * will show all files
string or group of $ ls a* will show all files whose first
characters. name is starting with letter 'a'
* $ ls *.c will show all files having
extension .c
$ ls Will show all files having
ut*.c extension .c but file name
must begin with 'ut'.
? Matches any $ ls ? will show all files whose
single character. names are 1 character long
$ ls fo? will show all files whose
names are 3 character long
and file name begin with fo
[...] Matches any one $ ls Will show all files beginning
of the enclosed [abc]* with letters a,b,c
characters
Example:
$ ls /bin/[a-c]*
Output:
The Metacharacters
Unix Shell provides various metacharacters which have special meaning while
using them in any Shell Script and causes termination of a word unless quoted.
Example:
? Matches with a single character while listing files in a directory and an * would
match more than one characters.
Here is a list of most of the shell special characters (also called metacharacters):
A character may be quoted (i.e., made to stand for itself) by preceding it with a \.
Example:
Hello ./test.sh: line 2: Word: command not found shell returned 127
Hello; Word
I have $1200
Quote Description
Single quote All special characters between these quotes lose their
special meaning.
Double Most special characters between these quotes lose their
quote special meaning with these exceptions:
$
`
\$
\'
\"
\\
Backslash Any character immediately following the backslash loses
its special meaning.
Back Quote Anything in between back quotes would be treated as a
command and would be executed.
Putting a backslash in front of each special character is tedious and makes the line
difficult to read:
echo \<-\$1500.\*\*\>\; update\?update\?
y∥ny‖n
There is an easy way to quote a large group of characters. Put a single quote ( ') at
the beginning and at the end of the string:
Any characters within single quotes are quoted just as if a backslash is in front of
each character. So now this echo command displays properly.
If a single quote appears within a string to be output, you should not put the whole
string within single quotes instead you would precede that using a backslash (\) as
follows:
VAR=ZARA
So this is not what you wanted to display. It is obvious that single quotes prevent
variable substitution. If you want to substitute variable values and to make invert
commas work as expected then you would need to put your commands in double
quotes as follows:
VAR=ZARA
Double quotes take away the special meaning of all characters except the
following:
Syntax: var=`command`
Example:
Following would execute date command and produced result would be stored in
DATA variable.
DATE=`date` echo "Current Date: $DATE"
While writing a shell script, there may be situations when you need to adopt one
path out of many available paths. In such cases you need to make use of
conditional statements that allow your program to make correct decisions and
perform right actions.
Unix Shell supports conditional statements, which are used to perform different
actions based on different conditions.
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.
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)
then
command(s)
else
command(s)
fi
We can use test command as condition of if condition as used in the below script.
$cat if_test.sh
#!/bin/sh
read ans
if test $ans ==’y’ –o $ans==’Y’
then
exit
else
fi
case...esac Statement
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:
case word in pattern1)
;;
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.
Example:
#!/bin/sh
COURSE=”DB”
case “$COURSE” in
;;
;;
;;
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
Syntax:
while condition
command(s)
done
Example:
a=0
while [ $a -lt 3 ]
do
echo $a
a=`expr $a + 1`
done
Output:
until loop
Syntax:
until condition # complement of while
do
command(s)
done
Example:
a=0
until [ ! $a -lt 3 ] do
echo $a a=`expr $a + 1`
done
Output:
for loop
For loop operate on lists of items. It repeats a set of commands for every item in a
list.
Syntax:
do
done
Example:
for var in 0 1 2 3 4 5
do
echo $var
done
Output:
Example:
do
cat ${filename}
done
String Handling
String handling with test command:
The expr is quite handy for finding the length of a string and extracting a sub-
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
Note that there are 6 dots preceding the sequence ..... This advanced regular
expression signifies that the first six characters of the string are to be ignored and
extraction should start from the 7th character. Two dots inside .... suggests that this
extraction is limited to two characters only (backslashes override the usual
interpretation of ‘()’).
$ str="abcdefghijk"
cdefghijk
$ str=”abcdefghijk” ;
Below will give the last occurrence of character 'a' from string str.
9.
6. Command Line Arguments
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:
$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
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.
$cat test.sh
#!/bin/sh
Let’s execute the above shell script “test.sh”. Remember to change File access
permission of script to execute
To get input from the keyboard, you use the read command. The read command
takes input from the keyboard and assigns it to a variable.
Example: read.sh
#!/bin/sh
read text
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
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
$ sh test.sh abc
For scripts where input expected is a file , validations can be incorporated for file
tests like whether the file given as input exists or not, whether it is empty or not,
whether it is readable or not and so on as per requirements.