INFO 212
Shell Scripting
• So far, we have used shells interactively.
• However, shells can also be used as programming
environments:
Shell scripting means running a script, as a
program, on a shell.
• Default shell on most Unix systems nowadays is bash
(Bourne-again shell):
bash is a derivative of the oldest shell known as
Bourne shell (sh).
2
Input/Output
• The basic I/O statements are:
echo for displaying text.
read for reading input from the keyboard.
• Shell script should be stored in a file with extension .sh
such as example1.sh.
• Then it can be executed as follows:
./example1.sh
bash example1.sh
• Make sure you have execution file permission:
chmod +x example1.sh
3
io.sh
• read statement takes all characters typed until the
[ENTER] key is pressed and stores them into the given
variable.
#!/bin/bash
echo Name a fruit?
read FRUIT
echo Vegetable?
read VEGGIE
echo $FRUIT and $VEGGIE are healthy foods
4
io.sh
• echo statement will print multiple arguments.
> bash io.sh
Name a fruit?
apple pie
Vegetable?
ice cream cake
apple pie and ice cream cake are healthy foods
echo eliminates redundant whitespace (spaces
and tabs) and leaves a single space between
arguments. 5
io.sh
• a programmer is most likely displaying text and would
benefit from a default behavior where spacing was
singularized.
• This behavior can be suppressed by enclosing the
desired output within double quotes.
• The string of multiple words is then treated as a single
argument.
echo “$FRUIT and $VEGGIE are healthy foods”
6
Special Symbols
• # symbol starts a comment, where everything after it is
considered part of the comment.
• $ symbol indicates that the rest of the string is the name
of a variable.
• \ symbol is an escape sequence and indicates that the
next character should be displayed literally; this allows
for the display of the reserved symbols in output.
7
Special Symbols
• The use of single quotes ‘’ indicates that everything
inside them should be displayed literally including any
special symbols.
• The braces {} can be used to enclose the name of a
variable when it is to be displayed adjacent to other text;
in this manner, the shell knows the extent of the variable
name.
8
symbols.sh
#!/bin/bash
# This is a comment
# Special symbols include # $ \ ’ {}
HI=Hello
echo HI
echo $HI
echo \$HI
echo '$HI'
echo "$HI"
echo "$HIJ"
echo "${HI}J"
12
Variables
• Variables do not need to be explicitly declared before
being used.
• The first time a new variable name is seen, the shell
programming environment allocates space for it
automatically.
• Unlike C, the type of data held by the variable is also
unimportant.
• There is only one type of variable, and no distinction is
made between text and numeric data, or between
different types of numeric data.
13
Variables
• All variables are stored as strings.
• Numeric operations can be performed upon variables,
but the variables are passed to the appropriate operator
as strings and then converted before the numeric
operation is performed.
• If a numeric result is stored in a variable, it is
automatically converted back to a string before storage.
• The idea is to relieve any burden upon the programmer
with regards to explicit data typing.
14
Variables
• By convention, variables are often named using all
uppercase letters. This allows them to be seen more
easily and differentiated from other code.
• If a variable is named using two or more words, then by
convention the underscore character is often used to
separate the words.
#!/bin/bash
ROCKS=4
echo Price?
read PRICE
echo "$ROCKS rocks for sale, $PRICE each"
15
Automatically Declared Variables
#!/bin/bash
echo Run with $# arguments
echo First three command line arguments:
echo $0
echo $1
echo $2
echo $3
echo PID is $$
> ./automatic.sh arg1 arg2 arg3
16
Loops
• Loops can be created in bash using either: for or while.
for varname in list
do
command1
command2
..
done
• for, in, do and done are keywords.
17
loops.sh
#!/bin/bash
for i in 1 2 5 tree frog
do
echo "file${i}.txt“
done
18
Loops
• You can also loop through using range of numbers in the
for loop “in” using brace expansion.
• Increment is 1 by default.
for num in {1..10}
do
echo "Number: $num"
done
19
Loops
• To edit loop list increment.
for num in {1..10..2}
do
echo "Number: $num"
done
20
loops2.sh
• while statement is used in shell scripting as it is used in
many languages, namely, for the processing of data of
unknown length.
#!/bin/bash
NAME=Unknown
while [ $NAME != "Fred" ]
do
echo Who are you?
read NAME
echo “Let me see ...”
done
21
echo Found you!
Let keyword
#!/bin/bash
a=2334 # Integer.
let "a += 1"
echo "a = $a " # a = 2335
22
Conditional
• if statement is the primary method of program flow
control in shell scripting.
• The if statement tests a condition; if the condition is true,
then the code inside the delimiters then and fi is
executed.
if [ conditional expression ]
then
statement1
statement2
. 23
fi
conditional.sh
#!/bin/bash
NAME="Fred“
if [ $NAME = "Fred" ]
then
echo Matches
fi
24
conditional.sh
#!/bin/bash
if [ $1 = "Fred" ]
then
echo Matches
fi
>./conditional.sh Fred 25
Test
• if statement (and while statement) use the test program
to evaluate a condition.
• The test program can be called by its full name, “test,” or
by a convenient shorthand alias using square brackets.
if [ conditional expression ]
then
statement1
statement2
.
fi 26
test.sh
#!/bin/bash
NAME="Joe“
if test $NAME = "Fred"
then
echo Hello Fred
fi
if [ $NAME = "Joe" ]
then
echo Hello Joe
fi 27
Test
• The square brackets syntax is usually preferred because
it is shorter and somewhat easier to read.
• When using the square bracket syntax, all arguments
within the square brackets must have preceding and
succeeding spaces.
28
Conditional
• if statement can contain else clauses, similar to most
programming languages.
if [ conditional expression ]
then
statement1
…
else
statement2
….
fi 29
conditional2.sh
#!/bin/bash
NAME="Joe“
if [ $NAME = "Fred" ]
then
echo Matches
else
echo No match
fi 30
Conditional
• Multiple if statements can be chained using the elif
statement.
if [ conditional expression ]
then
statement1
elif [ conditional expression2 ]
then
statement2
else
statement3
31
fi
conditional3.sh
#!/bin/bash
COUNT=99
if [ $COUNT -eq 100 ]
then
echo "Count is 100“
elif [ $COUNT -gt 100 ]
then
echo "Count is greater than 100“
else
echo "Count is less than 100“
fi 32
Conditional
• if statements can also be used to evaluate simple string
equivalencies, non-equality and other conditions.
• Use != to test for inequality.
• The -z option tests if a string is empty.
• The -n string tests if a string is not empty.
33
conditional4.sh
#!/bin/bash
NAME="Fred”
if [ "$NAME" != "Joe" ]
then
echo Where\’s Joe?
fi
34
conditional5.sh
#!/bin/bash
GHOST="“
if [ -z "$GHOST" ]
then
echo Boo!
fi
if [ -n "$GHOST" ]
then
echo I’m not a ghost.
35
fi
Conditional
• The flag -lt tests if the first argument is less than the
second.
• The flag -gt tests if the first argument is greater than the
second.
• The flags -le and -ge also test for equality but include the
case where the arguments are equal in the evaluation.
36
conditional6.sh
#!/bin/bash
i=7
j=9
if [ "$i" -lt "$j" ]
then
echo Lesser
fi
if [ "$i" -gt "$j" ]
then
echo Greater
fi
37
Conditional
• The flag -f tests whether or not a file with the given name
exists.
• The flags -r, -w and -x test whether or not the read, write,
and execute permissions for the file are set.
• The flag -d tests if the given filename is a directory.
38
conditional7.sh
#!/bin/bash
FILE=conditional7.sh
if [ -f "$FILE" ]
then
echo FILE exists
fi
if [ -x "$FILE" ]
then
echo FILE is executable
39
fi