Professional Documents
Culture Documents
Shell Programming
Unix Shell programming:
– What is shell
• Types of shell
– Shell scripts.
• Definition.
• Uses of shell scripts.
• Writing shell scripts.
• Examples
Unix Architecture
User UNIX Interface: SHELL
Provides command line as an interface between
the user and the system
Is simply a program that starts automatically when
you login
Uses a command language
– Allows programming (shell scripting) within the shell
environment
• Uses variables, loops, conditionals, etc.
– Accepts commands and often makes system calls to
carry them out
Types of Unix Shell
The most commonly used
SH(Bourne Shell)
CSH(C shell)
KSH(Korn shell)
#!/path/to/shell
Usually anything following ( # ) is
interpreted as a comment and ignored but
if it occurs on the first line with a ( ! )
following it is treated as being special and
the filename following the ( ! ) is
considered to point to the location of the
shell that should interpret the 1script.
What is a shell script ????
Shell scripts
A shell script is a text file with Unix
commands in it.
Shell scripts usually begin with a #! and a
shell name (complete pathname of shell).
– Pathname of shell be found using the which
command.
– The shell name is the shell that will execute
this script.
• E.g: #!/bin/bash
Shell scripts (contd.)
#!/bin/sh
echo 'msg="Hello World!"' > hello
echo 'echo $msg' >> hello
chmod 700 hello
./hello
Output –
This would cause "msg="Hello World!" to be echoed and
redirected to the file hello, "echo $msg" would then be echoed and
redirected to the file hello but this time appended to the end.
The chmod line changes the file permissions of hello so that we can
execute it.
The final line executes hello causing it output "Hello World".
Setting Variables
Values of shell variable are all character-
based: A value is formally defined to be a
list of zero or more
elements, and an element is formally
defined to be a character string. In other
words, a shell variable
consists of an array of strings.
For example,
set X
Command Line Arguments as a variable
treated as special variables within the script
the reason I am calling them variables is because they
can be changed with the shift command
The command line arguments are enumerated in the
following manner $0, $1, $2, $3, $4,$5, $6, $7, $8 and
$9
$0 is special in that it corresponds to the name of the
script itself.
$1 is the first argument, $2 is the second argument
and so on.
To reference after the ninth argument you must
enclose the number in brackets like this ${nn}.
You can use the shift command to shift the arguments
1 variable to the left so that $2 becomes $1, $1
becomes $0 and so on,
There are some special built in variables
(command line argument):
1. $# -represents the parameter count.
-Useful for controlling loop constructs that need to
process each parameter.
1. $@ -expands to all the parameters separated by
spaces.
-Useful for passing all the parameters to some other
function or program.
1. $ - expands to the flags (options) the shell was
invoked with.
-Useful for controlling program flow based on the flags
set.
1. $$ - expands to the process id of the shell
innovated to run the script.
-Useful for creating unique temporary filenames relative
to this instantiation of the script.
Notes on expr
expr supports the following operators:
– arithmetic operators: +,-,*,/,%
– comparison operators: <, <=, ==, !=, >=, >
– boolean/logical operators: &, |
– parentheses: (, )
– precedence is the same as C, Java
Arithmetic Expansion
Arithmetic expansion is also allowed and comes
in the form:
Syntax $((expression))
The value of the expression will replace the
substitution.
Eg:
!#/bin/sh
echo $((1 + 3 + 4))
Example:
if test “$word1” = “$word2”
then
echo “Match”
fi
Example
– You can use semicolon (;) ends a command the same way a
NEWLINE does.
if [ … ]; then
……
fi
#! /bin/bash
if grep "UNIX" myfile >/dev/null
then
echo UNIX occurs in myfile
else
echo No!
echo UNIX does not occur in myfile
fi
Example
nested if…then…else if…then…else
#!/bin/sh
if [ "$1" = "1" ]
then
echo "The first choice is nice"
elif [ "$1" = "2" ]
then
echo "The second choice is just as nice"
elif [ "$1" = "3" ]
then
echo "The third choice is excellent"
else
echo "I see you were wise enough not to choose"
echo "You win"
fi
Using colon in shell scripts
Sometimes, we do not want a
statement to do anything.
– In that case, use a colon ‘:’
• if grep UNIX myfile > /dev/null
• then
•:
• fi
• Does not do anything when UNIX is found
in myfile .
Debugging Shell Scripts
Display each command before it runs the
command
– Set the –x option for the current shell
• $set –x
– Use the –x to invoke the script
• $sh –x command arguments
– Add the set command at the top of the script
• set –x
Then each command that the script executes
is preceded by a plus sign (+)
– Distinguish the output of trace from any output
that the script produces
Turn off the debug with set +x
Do...While
while list
do list
done
Do...While example
Example –
#!/bin/sh
count=$1 # Initialise count to first parameter
while [ $count -gt 0 ] # while count is greater than 10 do
do
echo $count seconds till supper time!
count=$(expr $count -1) # decrement count by 1
sleep 1 # sleep for a second using the Unix sleep command
done
echo Supper time!!, YEAH!! # were finished
Output -
If called from the commandline with an argument of 4 this script will
output
4 seconds till supper time!
3 seconds till supper time!
2 seconds till supper time!
1 seconds till supper time!
Supper time!!, YEAH!!
for loops
for loops allow the repetition of a command for
a specific set of values.
Syntax:
for var in value1 value2 ...
do
command_set
done
– command_set is executed with each value of var
(value1, value2, ...) in sequence
for… in
Structure
for loop-index in argument_list
do
commands
done
Example:
for file in *
do
if [ -d “$file” ]; then
echo $file
fi
done
Example for and for in
#!/bin/sh
fruitlist="Apple Pear Tomato Peach Grape"
for fruit in $fruitlist
do
if [ "$fruit" = "Tomato" ] || [ "$fruit" = "Peach" ]
then
echo "I like ${fruit}es"
else
Unix Shell Scripting Tutorial
5
echo "I like ${fruit}s"
fi
done
Output
I like Apples
I like Pears
I like Tomatoes
I like Peachs
I like Grapes
The while loop
While loops repeat statements as long as
the next Unix command is successful.
Works similar to the while loop in C.
while
Structure
while test_command
do
commands
done
Example:
while [ “$number” –lt 10 ]
do
……
number=`expr $number + 1`
done
The until loop
Until loops repeat statements until the
next Unix command is successful.
Works similar to the do-while loop in C.
until
Structure
until test_command
do
commands
done
Example:
secretname=jenny
name=noname
until [ “$name” = “$secretname” ]
do
echo “ Your guess: \c”
read name
done
Example
#! /bin/bash
x=1
until [ $x -gt 3 ]
do
echo x = $x
x=`expr $x + 1`
done
do
if [ $index –le 3 ]; then
echo continue
continue
fi
echo $index
if [ $index –ge 8 ]; then
echo “break”
break
fi
done
case
Structure
case test_string in
pattern-1 )
commands_1
;;
pattern-2 )
commands_2
;;
……
esac
default case: catch all pattern
*)
case
Special characters used in patterns
Pattern Matches