Lab Manual 03 Shell Scripting PDF
Lab Manual 03 Shell Scripting PDF
Sciences Operating
System Lab - 03
Lab Manual
Contents
Objective ........................................................................................................................................................ 2
Shell Scripting ................................................................................................................................................ 2
Variables ........................................................................................................................................................ 5
Comments...................................................................................................................................................... 6
‘echo’ & ‘read’ Statements ............................................................................................................................ 6
Accessing Arguments ..................................................................................................................................... 7
Arithmetic Operations ................................................................................................................................... 8
Conditional Statements ................................................................................................................................. 8
‘case’ Structure ............................................................................................................................................ 11
Iterative Structure ....................................................................................................................................... 12
Functions ..................................................................................................................................................... 14
Special Symbols ........................................................................................................................................... 14
Lab Activity .................................................................................................................................................. 15
Coursera....................................................................................................................................................... 15
Reference Tutorial ....................................................................................................................................... 15
Objective
The lab examines the use of shell scripts as a way to write programs that accomplish various
forms of processing in a Linux environment.
Shell Scripting
We have already talk about shell programming/scripting in Lab Manual 02 – Introduction to Shell
Scripting. A shell script can be viewed as a high level program that is created with a simple text
editor. Once created, a user may execute a shell script by simply invoking the filename of the shell
script. It is unnecessary to compile the shell script first. Rather, each time the shell script
is invoked, a shell interprets or compiles the shell script as it executes it.
A shell script invokes commands that you can issue through a command-line. In addition, a shell
script also allows for more sophisticated processing, such as decision making and repetition for
the work it invokes. In this manner, a shell script can be written to accomplish a series of tasks
more easily and quickly than if the user had to type the commands for the tasks every time. Shell
scripts are also a common way to schedule jobs to be automatically invoked by the system at
specific times.
To create a shell script file, create a new file with any name and with extension ‘.sh’. Note you can
also create the shell script file without the extension specified but then the file editor e.g. gedit’s
content will no longer be content-aware. The demonstration of creating the file is shown below:
To invoke a shell script simply type in your terminal: ‘./’ followed by the filename with the extension
‘.sh’. For example, if I want to execute shell script having filename: ‘shelly.sh’ I would execute it
as shown in the screenshot below.
Make sure the file i.e. in my case ‘shelly.sh’ is executable. In case the file is not executable you
need to add access permission using ‘chmod’ command which we discussed in lab manual 02.
Notice the path when I invoke shell script. The first one is: ‘./Desktop/shelly.sh’ which specified
that in folder Desktop there is an executable filename ‘shelly.sh’ which it simply executed. Now
when I tried ‘./shelly.sh’ it gave me the error of no such file or directory because the parent
directory of Desktop does not contain that file. After changing directory to Desktop, I retried the
command and it executed. Hence in invoking a shell script you need to specify the path where the
filename is. Otherwise the system won’t be able to find it and/or execute it.
Variables
Like most other programming languages, a shell script can use variables to store data for future
retrieval. The names for shell script variable may consist of alphabetic letters, underscores, or
digits (but not in the beginning). Letters are case sensitive. There are two types of variables used
in shell programming.
1. System Variables
2. User Defined Variables
System variables are created and maintained by Linux. These types of variables will be denoted
in upper case letters. To get the details of available system variables, issue the command $set.
Users variables are defined by users. They are usually defined in lower case letters.
To store a value in a variable within a shell script, specify the assignment as shown below.
X=1
y=100.25
message=’hellow world’
In the figure above, the value 1 is stored in x, the value 100.25 in y, and the string value ‘hello
world’ in message. When a variable appears initially in a script in an assignment statement, the
script automatically declares the variable with the appropriate data type to hold the assigned
value.
To obtain the value stored in the variable, specify the $ symbol followed by the variable name. As
shown below:
echo $message
newMessage=$message
echo “The message is: $newMessage”
In the example above, the first line shows how to write the value of the variable ‘message’ to the
screen, the second line, assigns the value of the variable ‘message’ to the variable ‘newMessage’
and lastly, the third line shows how to write the value of a variable along with other text. Notice
that the example uses double quotes to enclose the text and variable name. You may omit the
double quotes, but you cannot use single quotes. The use of single quotes in this example will
actually instruct echo to write the enclosed contents exactly as they appear.
Comments
A comment is a line or part of the line that not executed in any programming language. In shell
script, a comment starts with the # symbol and continues to the end of that line. This implies that
a comment may either take an entire line if # appears as the first character on any line in a shell
script. Alternatively, it may appear on the same line with some other action, after the action
specification. The example below will make this paragraph more meaningful.
To take input from the keyboard into a shell script variable, you can use the read command
followed by the variable. Examples below shows how a shell script can prompt the user for a value
and read that value into a variable.
#printing a prompt and reading input
read num
#utilizing read to print a prompt and read input into two variables
read -p “Enter your first name and last name: “ FirstName LastName
Accessing Arguments
You can send arguments when you invoke a shell script, the arguments can be in any number.
The shell store those arguments passed in variable $n where n = {1,2,3…9} and you pass the
arguments just like in any other command. The below shell script and terminal shows the
execution of a shell script which is using command line arguments.
The screenshot below shows the execution of the above shell script.
Other arguments available in shell script and their usage/description is provided in the table below.
Num=10
(( Double = 2 * $Num ))
echo “Twice the number is $Double”
(( DoublePlus1 = 2 * $Num + 1 ))
echo “Twice the Number Plus 1 is $DoublePlus1”
(( DoubleQPlus1 = 2 * ($Num +1) ))
echo “Twice the number plus 1 is $DoubleQPlus1”
(( half = $Num/2 ))
echo “Half the number is $half”
Some arithmetic operators which are commonly used is given below in the table:
When comparing numeric values or text values in a condition, you can use the comparison
operators listed in the table below. Be careful to include space before and after the operator to
separate the operator from the variables and/or values on its left and right side. Otherwise, the
shell may incorrectly evaluate the condition
Shell script supports logical operators such as OR and AND to specify a compound condition such
as condition that contain multiple comparisons. You can also use logical not to negate a condition.
Table below shows the logical operator with example of their use.
Taking a look at a simple one-branch decision shown below, shows how to specify a simple branch
statement with if-then-fi. The example below takes two numbers and reports if the first one is
smaller than the other one.
For a situation that requires more than one condition and/or more than two branches. You can
incorporate elif statement into one of the previous decision structure. The example below shows
the use of if-then-elif-then-else statement. The condition for elif statement is same as if statement.
read -p “Enter First Number: ” num1
read -p “Enter Second Number: ” num2
if [[ $num1 < $num2 ]]; then
echo “$num1 is smaller than $num2”
elif [[ $num1 > $num2 ]]; then
echo $num1 “is greater than” $num2
else
echo $num1 “is equal to” $num2
fi
While all the previous examples with if statement and conditions involved numeric variables and
values, you can also compare text variables and text values with the operator listed previously.
Such text comparisons refer to the ASCII value of the individual text characters on left and right
sides. Here the first character is compared, followed by the second then the third and so on. Until
it can determine whether the given comparison is true or false. Additionally, keep in mind that text
is considered case sensitive and capital letters have lower ASCII values than the lowercase
counterparts.
Consequently, a comparison of two string is true when both sides have exactly same text and
case. The example below shows how to use text variable in string comparison however, the
example below may exist potential error.
else
However, imagine that $YN has no value then the condition becomes [[ = ‘YES’ ]], resulting in a
runtime error where the shell script does not execute correctly. To fix this problem you need to
treat both sides of the comparisons as a string with an added letter. To ensure that each side
contains at least one letter. The fix is demonstrated in an example below.
if [[ “x$YN” = ‘xYES’]]; then
echo “Yes is specified”
else
echo “You did not specify yes”
fi
In the script above we have added the letter ‘x’ on both sides however, it could have been any
other letter. The reason of adding an extra letter on both sides is because how a shell script
interprets the script contents as it executes the script content. In this case, when executing if
statement using any variable the shell script uses its value rather than the variable. If the variable
is empty, the side of that comparison is considered empty hence resulting in a runtime error
generated by the shell executing that script.
In a situation where you wish to compare the text variable’s value without distinguishing of being
upper case or lower case. One can use logical operator to compare against both lowercase and
uppercase forms of the text. The example of this demonstration is shown below.
Another form of a condition containing numeric variables or values involves the test operator. It
allows you to specify a numeric condition by omitting enclosing brackets entirely and preceding
the word test. The example below demonstrates the test command to determine whether one
numeric variable contain smaller value than the other one.
‘case’ Structure
Alternative form of shell script branching involves case structure. It allows the specification of a
controlling value by a case statement. Following the case statement is a series of values or
patterns, each with a branch of one or more statements. Like switch-case structure in C/C++, the
shell compares the controlling value against the values to find a match, starting with the first and
continuing till the last. When a match is found, the shell executes the corresponding branch. You
can also include a default branch that is executed if the controlling value does not mtch any of the
values or pattern.
Iterative Structure
To accomplish iteration in a shell script, you have a number of mechanisms available for that
purpose. These involves while loops, for loops and a form of while loop called until. The syntax
of these stated iterative loops is shown below.
Example of utilizing while loop, the below examples takes then number of directories to be
created then using while loop it takes the names of those directories from user and tries to
create them.
for i in {1..4}
do
read -p “Enter the name of the directory: ” dirName
mkdir $dirName
if [[ $? = 1 ]] ; then
echo “Directory creation failed”
fi
done
The demonstration of the form of while loop aka until is shown below
Min() {
if [[ $1 -lt $2 ]]; then
Smallest=$1
else
Smallest=$2
fi
}
read -p “Enter two whole numbers, Separated by space: ” N1 N2
Min $N1 $N2
echo “The smallest is: ” $Smallest
At first line of a function definition, it specifies the function name and an empty set of parentheses.
Unlike many other programming languages, the parentheses at the first line of a function definition
are always empty, whether or not you supply arguments to the function. The remainder of the
function definition consists of the commands in the function body enclosed with { and } braces. To
access any arguments with a function, use the shell script variable explained in ‘Accessing
Arguments’ section.
Special Symbols
The following are the meaning of symbols used in shell scripting:
Coursera
The Unix Workbench (cover Week 3 for Lab 3)
https://www.coursera.org/learn/unix
https://seankross.com/the-unix-workbench/
Reference Tutorial
https://www.shellscript.sh