UNIX Operating System VVFGC, Tumkur
Chapter - 06
Shell Programming
Shell:
A shell is a program that provides an interface between a user and an operating
system(OS) kernel.
An OS starts a shell for each user when the user in or opens a terminal or console
windows
The shell scripts have syntax just like any other programming language
Compare to C and C++ python it is easy to get started
1. Shell keyword(if, else, break)
2. Shell commands(cd, ls, cat, man)
3. Functions
4. Controls flow(if….then…..else, case & shell loops)
Features:
You can program the shell quickly and simple
It may be used interactively and non-interactively
It is input and output redirection & pipelines
It provides a set of built-in command
They do not requires the compilation before execution
Support type less variable
Advantage and Disadvantges:
Advantages:
Writng shell script are uch quicker
Quick start
Interactive debugging
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 1
UNIX Operating System VVFGC, Tumkur
Disadvantages:
A single mistake can change the command which might be harmful
Slow execution speed
Not well suited for large and complwx task
Types of shell:
1. The Bourne shell
2. The Korn shell
3. The GNU Bourne
1. The Bourne shell:
It denoted as sh
It written by Steve Bourne at AT & T Bell labs
It is original Unix shell (faster and more preferred)
It lacks features for interactive use like the ability to recall previous command
It also lacks built-in- arithmetic and logical expression handling
2. The Korn Shell
It denotes as ksh
It includes features like array function and string manipulation facilities
It is faster than C shell
3. The GNU Bourne
It denotes as bsh
Bash is the default shell in the Operating System
Writing and executing the shell script:
1. Create a file using a vi editor (or any other editors). Name the script file with extension.sh
2. Write some code.
3. Save the script file as filename .sh
4. For executing the scripting type sh filename.sh
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 2
UNIX Operating System VVFGC, Tumkur
Debugging shell script:
We can debug a shell is to specify the debug option when executing the
script. Ex: bash-xv sample.sh
Variables:
Shell variables are used to store the data by shell only.
1. Envirnoment variable
2. User defined variable
Envirnoment variable:
These variable are the part of the variables used to store the data by the system itself
These variable always in capital letter only
Variables Meaning
PS1 this is first prompt setting in UNIX($)
PS2 this is second prompt setting in UNIX(>)
PATH whether we are used absoult and relative path
HOME it stores the current root directory
LOGNAME it stores the login name of the user
User defined variables:
User defined variables are the shell variables are defined by the user
Syntax: Variable_name=Variable_value
Mathematical Expression:
Expr command:
This command is used to perform mathematical calculation
Syntax: `expr operand1 operator operaand2`
Example:
Clear
Echo “enter two number”
Read a b
Echo “sum of 2 numbers expr $a+$b
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 3
UNIX Operating System VVFGC, Tumkur
Arithmetic Operators:
Operator Name Use Example
result=
+ Addition It adds two operands a+b
– Subtraction It subtract second operand from first one result= a-b
result=
* Multiplication Multiply two operands a*b
16/3
Return the quotient after diving first operand from
result = 5
/ Division second operands
16/ 3
Return remainder after dividing first operand from
result = 1
% Modulo second operand
Conditional Control Statement:
Conditional Statements: There are total 5 conditional statements which can be used in bash
programming
1. if statement
2. if-else statement
3. if..elif..else..fi statement (Else If ladder)
4. if..then..else..if..then..fi..fi..(Nested if)
5. switch statement
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 4
UNIX Operating System VVFGC, Tumkur
Their description with syntax is as follows:
if- statement:
This block will process if specified condition is true
Syntax:
if [ expression ]
then
statement
fi
if-else-statement:
If specified condition is not true in if part then else part will be execute.
Syntax
if [ expression ]
then
statement1
else
statement2
fi
if..elif..else..fi statement(Else if ladder)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If
expression1 is true then it executes statement 1 and 2, and this process continues. If none of the
condition is true then it processes else part.
Syntax
if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 5
UNIX Operating System VVFGC, Tumkur
statement3
statement4
.
.
else
statement5
fi
if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies then it again checks another
condition.
Syntax:
if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
switch statement:
case statement works as a switch statement if specified value match with the pattern then it will
execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is
executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
Syntax:
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 6
UNIX Operating System VVFGC, Tumkur
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Test command:
A test command is a command that is used to test the validity of a command. It checks whether
the command/expression is true or false. It is used to check the type of file and the permissions
related to a file.
Syntax:
test [expression]
1. Flags for files and directories
2. Flags for text strings
3. Flags for comparison of numbers
Flags for files and directories:
test -e filename: Checks whether the file exists or not.
test -d filename: Checks whether the file is a directory or not.
test -f filename: Checks whether the file is a regular file or not.
test -s filename: Checks whether the file is empty or not.
test -r filename: Checks whether the file is readable or not.
test -w filename: Checks whether the file is writable or not.
test -x filename: Checks whether the file is executable or not.
Flags for text strings
string1 = string2: Checks whether the two strings are equal or not. And returns 0 if the
two strings are equal and returns 1 if the two strings are not equal.
string1 != string2: Checks whether the two strings are not equal or not. And returns 0
if the two strings are not equal and returns 1 if the two strings are equal.
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 7
UNIX Operating System VVFGC, Tumkur
-n string: Checks whether the string is empty or not. And returns 1 if the string is
empty and returns 0 if the string is not empty.
Flags for comparison of numbers
num1 -eq num2: Checks whether the two numbers are equal or not.
num1 -ne num2: Checks whether the two numbers are not equal or not.
num1 -gt num2: Checks whether the first number is greater than the second number or
not.
num1 -ge num2: Checks whether the first number is greater than or equal to the second
number or not.
num1 -lt num2: Checks whether the first number is less than the second number or not.
num1 -le num2: Checks whether the first number is less than or equal to the second
number or not.
Logical Operators:
Logical Operators : They are also known as boolean operators. These are used to perform
logical operations. They are of 3 types:
Logical AND (&&): This is a binary operator, which returns true if both the operands
are true otherwise returns false.
Logical OR (||): This is a binary operator, which returns true is either of the operand is
true or both the operands are true and return false if none of then is false.
Not Equal to (!): This is a unary operator which returns true if the operand is false and
returns false if the operand is true.
Example:
read -p 'Enter a : ' a
read -p 'Enter b : ' b
if(($a == "true" & $b == "true" ))
then
echo Both are true.
else
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 8
UNIX Operating System VVFGC, Tumkur
echo Both are not true.
fi
if(($a == "true" || $b == "true" ))
then
echo Atleast one of them is true.
else
echo None of them is true.
fi
if(( ! $a == "true" ))
then
echo "a" was initially false.
else
echo "a" was initially true.
fi
Case – esac statement:
Another way of controlling the sequence of execution is using the case control statement.
Syntax:
Case $variable in
Match-1)
Command_to_execute_for_1
;;
Match-2)
Command_to_execute_for_2
;;
Match-3)
Command_to_execute_for_3
;;
.
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 9
UNIX Operating System VVFGC, Tumkur
.
.
*)command_to_execute for_no_match
;;
Match_1 and match_2 are the case lables which identify the potential choices of action.
When a case statement is evaluated the values of the variables is matched one by one
against potential choice
The pair of semicolons (;;) marks the end of the statement
The keyword esac denotes the end of case
The last case “*)” represents the default clause of case control instruction
Looping Statements in Shell Scripting:
There are total 3 looping statements which can be used in bash programming
1. while statement
2. for statement
3. until statement
To alter the flow of loop statements, two commands are used they are,
1. break
2. continue
while loop:
The while loop is used when we want to repeated something a fixed number of times or till the
condition is satisified.
Syntax:
While [ test condition ]
do
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 10
UNIX Operating System VVFGC, Tumkur
Command_block
Done
for loop:
It repeats a set of commands for every item in a list.
Syntax
for variable in value1 value2 value3…..value n
Do
statement
done
until loop:
The until loop is executed as many as times the condition/command evaluates to false. The
loop terminates when the condition/command becomes true.
Syntax:
until control-command
do
command-block
done
Break:
The break statement is used to terminate the loop and can be used within a while, for, until, and
select loops
Syntax:
Break;
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 11
UNIX Operating System VVFGC, Tumkur
Continue:
Continue is a command which is used to skip the remaining command inside the loop for the
current iteration in for, while, and until loop
Syntax:
Continue;
Command Line Arguments:
1. Removal of extra spaces
2. Variable evalution
3. Command substitution
4. Redirection
5. Filename substitution
6. Command execution
7. Search path
8. Semicolon interpretation
Positional parameters:
$0 $1 $2 $3
My-scripts args1 args2 args3a
$*
1. $0 – Script name or filename
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 12
UNIX Operating System VVFGC, Tumkur
2. $# - Number of arguments that were typed on the command line
3. $* - Complete set of positional parameter as a single string
4. $1-$9: Positional parameter representing command line arguments
5. $?: Exit status of the previously executed command
Set command:
The set command is used to set command values to particular positional arguments that will
usedby the programs.
Ex:
Set ` date `
Echo “today is
$1” Echo “Month
is $2” Echo
“Time is: $3”
Echo “year is $4”
In the above program we have to set “date” command values to positional arguments.
Unset Command:
The unset command is used to destroy or delete setted values from particular positional
arguments.
Ex:
Set ` date `
Echo “today is
$1” Echo
“Month is $2”
Echo “Time
is: $3” Echo
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 13
UNIX Operating System VVFGC, Tumkur
“year is $4”
Set –x //unsetting the values In the above program we have to unset “date” command
values from positional arguments.
Shift Command:
The shift command in UNIX is used to move the command line argument to one position
left.
The first argument is lost when we use this command.
Shifting command line arguments one but one without changing the variable name.
The value in $2 moves to $1, the value in $3 moves $2, and so on.
By default this operator will shift 1 place, but if we want to shift multiple places shifting
thenwe can use that number along with this operator.
Ex:
Echo” the total number of command line arguments
are: $#”Set ` date`
Echo” these arguments
are: $#” Echo “ $1 $2 $3
$4 $5”
Shift
Echo “$1 $2 $3 $4 $5”
In the above program we are going to shift arguments which are present in date command,
here
$1 is replaced by $2 and $2 argument is replaced by $3 and so on.
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 14
UNIX Operating System VVFGC, Tumkur
Internal Field separator (IFS)
a. An IF defines character(s) used to separate a pattern into token for some operation.
b. IFS typically include the space, tab and the newline.
c. The shell treats each character of $IFS as a delimiter and splits the result of the
otherexpansions into words on these characters.
d. If IFS unset pr its value is exactly <space> <tab> and <newline> at the beginning
andend of the results of the previous expansions are ignored.
Prepares by: Pavithra S.M, Asst. Professor Dept. of BCA Page 15