OS Lab 2 Shell Script
OS Lab 2 Shell Script
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 1
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
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 2
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 3
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 4
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”
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 5
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.
# I am a comment, I will not be executed echo ‘hellow from comment’; date; pwd #this line will be
executed till the # symbol appears
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 6
#printing a prompt and reading input echo
#utilizing read to print a prompt and read input into two variables read -p
“Enter your first name and last name: “ FirstName LastName echo -n “First
Name: $FirstName” “LastName: ” echo -n $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.
“Argument 2: $2”
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 7
equivalent to $1 $2.
All the arguments are individually double quoted. If a script receives two
5 $@
arguments, $@ is equivalent to $1 $2.
6 $? The exit status of the last command executed.
The process number of the current shell. For shell scripts, this is the process ID
7 $$
under which they are executing.
8 $! The process number of the last background command.
Arithmetic Operations
In shell script, you can perform arithmetic operations, in calculations or within the formula. You must enclose the
formula or calculation with a set of double parentheses (( )). There should be no space between the two right and left
parentheses. The example below shows how to use arithmetic operations.
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
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 8
1 -eq = Equal to [[ $count -eq 10 ]]
2 -ne != Not equal to [[ $total -ne 1000 ]]
3 -lt < Less than [[ $balance -lt 0 ]]
4 -le <= Less than or equal to [[ $C -le $B ]]
5 -gt > Greater than [[ 5 -gt 6 ]]
6 -ge >= Greater than or equal to [[ $total -ge $subtotal ]]
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 9
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.
if [[ $YN = ‘YES’ ]]; then
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.
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 10
read -p “Enter y (yes) or n (no): ” YN
if [[ “x$YN” = “xy” || “x$YN” = “xY” ]]; then
echo “you specified yes” else
echo “you specified no”
fi
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 11
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.
The utilization of for loop of the same script requirement is demonstrated in an example below.
The demonstration of the form of while loop aka until is shown below
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 12
read -p “Enter the number of directories to be created: ” numDir
until [[ $numDir -eq 0 ]] do read -p “Enter the name of the
directory: ” dirName mkdir $dirName
if [[ $? = 1 ]] ; then
echo “Directory creation failed”
fi
(($numDir--)
done
Functions
To help modularize and reuse shell script code, you can use functions within a shell script like you can in other
programming languages. A short example shows a shell script that defines a function named ‘Min’ that prints the
smaller of two arguments. The script asks the user to input two numbers and calls the Min function to report the
smaller number from the two provided.
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.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 13
Special Symbols
The following are the meaning of symbols used in shell scripting:
Lab Exercise
1. Write scripts /commands / syntax to print a message “Welcome to the World of Shell Scripting” 10 times.
2. Write scripts /commands / syntax to take input and print your name, degree program information, batch No
and course title.
3. Write scripts /commands / syntax that take input and check the number is positive or negative.
4. Write scripts /commands / syntax that take input and check the number is prime or not.
5. Write scripts /commands / syntax that take input and check the maximum and minimum of 5 input numbers.
6. Write scripts /commands / syntax to generate the Fibonacci series.
7. Write scripts /commands / syntax to find out the factorial of given input number.
8. Write scripts /commands / syntax for moving files into three subdirectories directories:
a. shelldir, cdir, jpgdir according to their extensions.
LAB#02: SHELL SCRIPTING & VI, ALIASES, ENVIRONMENT VARIABLES AND SUBSHELLS 14