LINUX UNIT IV
LINUX UNIT IV
SHELL PROGRAMMING
An improved version of the vi editor which is called the VIM has also been made available
now. Here, VIM stands for Vi IMproved.
You can use the vi editor to edit an existing file or to create a new file from scratch. You can
also use this editor to just read a text file.
1
vi filename
Creates a new file if it already does not exist, otherwise opens an existing file.
2
vi -R filename
Opens an existing file in the read-only mode.
1|Page
3
view filename
Opens an existing file in the read-only mode.
Following is an example to create a new file testfile if it already does not exist in the current
working directory −
$vi testfile
The above command will generate the following output −
|
~
~
~
~
~
~
~
~
~
~
~
~
"testfile" [New File]
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused
line. If a line does not begin with a tilde and appears to be blank, there is a space, tab, newline,
or some other non-viewable character present.
You now have one open file to start working on. Before proceeding further, let us understand
a few important concepts.
2. Operation Modes
While working with the vi editor, we usually come across the following two modes −
2|Page
vi always starts in the command mode. To enter text, you must be in the insert mode for
which simply type i. To come out of the insert mode, press the Esc key, which will take you
back to the command mode.
Hint − If you are not sure which mode you are in, press the Esc key twice; this will take you
to the command mode. You open a file using the vi editor. Start by typing some characters
and then come to the command mode to understand the difference.
3. Getting Out of vi
The command to quit out of vi is :q. Once in the command mode, type colon, and 'q', followed
by return. If your file has been modified in any way, the editor will warn you of this, and not
let you quit. To ignore this message, the command to quit out of vi without saving is :q!. This
lets you exit vi without saving any of the changes.
The command to save the contents of the editor is :w. You can combine the above command
with the quit command, or use :wq and return.
The easiest way to save your changes and exit vi is with the ZZ command. When you are in
the command mode, type ZZ. The ZZ command works the same way as the :wq command.
If you want to specify/state any particular name for the file, you can do so by specifying it
after the :w. For example, if you wanted to save the file you were working on as another
filename called filename2, you would type :w filename2 and return.
1
k - oves the cursor up one line
3|Page
2
j - Moves the cursor down one line
3
h - Moves the cursor to the left one-character position
4
l - Moves the cursor to the right one-character position
There are many other ways to move within a file in vi. Remember that you must be in the
command mode (press Esc twice). The following table lists out a few commands to move
around the file −
5. Control Commands
The following commands can be used with the Control Key to performs functions as given in
the table below −
a) Editing Files
To edit the file, you need to be in the insert mode. There are many ways to enter the insert
mode from the command mode −
1
i - Inserts text before the current cursor location
4|Page
2
I - Inserts text at the beginning of the current line
3
a - Inserts text after the current cursor location
4
A - Inserts text at the end of the current line
5
o - Creates a new line for text entry below the cursor location
6
O - Creates a new line for text entry above the cursor location
b) Deleting Characters
Here is a list of important commands, which can be used to delete characters and lines in an
open file −
1
x - Deletes the character under the cursor location
2
X - Deletes the character before the cursor location
3
Dw - Deletes from the current cursor location to the next word
4
d^ - Deletes from the current cursor position to the beginning of the line
5
d$ - Deletes from the current cursor position to the end of the line
6
D - Deletes from the cursor position to the end of the current line
7
Dd - Deletes the line the cursor is on
5|Page
As mentioned above, most commands in vi can be prefaced by the number of times you want
the action to occur. For example, 2x deletes two characters under the cursor location
and 2dd deletes two lines the cursor is on.
6. Change Commands
You also have the capability to change characters, words, or lines in vi without deleting them.
Here are the relevant commands −
1
cc - Removes the contents of the line, leaving you in insert mode.
2
cw - Changes the word the cursor is on from the cursor to the lowercase w end of the
word.
3
r - Replaces the character under the cursor. vi returns to the command mode after the
replacement is entered.
4
R - Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting.
5
s - Replaces the current character with the character you type. Afterward, you are left in
the insert mode.
6
S - Deletes the line the cursor is on and replaces it with the new text. After the new text
is entered, vi remains in the insert mode.
6|Page
S.No. Command & Description
1
yy - Copies the current line.
2
yw - Copies the current word from the character the lowercase w cursor is on, until the end
of the word.
3
p - Puts the copied text after the cursor.
4
P - Puts the yanked text before the cursor.
7|Page
I Variables
A variable is a character string to which we assign a value. The value assigned could be a
number, text, filename, device, or any other type of data.
A variable is nothing more than a pointer to the actual data. The shell enables you to create,
assign, and delete variables.
a) Variable Names
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _).
_ALI
TOKEN_A
VAR_1
VAR_2
Following are the examples of invalid variable names −
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
The reason you cannot use other characters such as !, *, or - is that these characters have a
special meaning for the shell.
b) Defining Variables
variable_name=variable_value
For example −
NAME="Zara Ali"
The above example defines the variable NAME and assigns the value "Zara Ali" to it. Variables
of this type are called scalar variables. A scalar variable can hold only one value at a time.
8|Page
Shell enables you to store any value you want in a variable. For example −
VAR1="Zara Ali"
VAR2=100
c) Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ($) −
For example, the following script will access the value of defined variable NAME and print it
#!/bin/sh
NAME="Zara Ali"
echo $NAME
The above script will produce the following value −
Zara Ali
d) Read-only Variables
Shell provides a way to mark variables as read-only by using the read-only command. After
a variable is marked read-only, its value cannot be changed.
For example, the following script generates an error while trying to change the value of
NAME −
#!/bin/sh
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"
The above script will generate the following result −
/bin/sh: NAME: This variable is read only.
II Unsetting Variables
Unsetting or deleting a variable directs the shell to remove the variable from the list of
variables that it tracks. Once you unset a variable, you cannot access the stored value in the
variable.
9|Page
Following is the syntax to unset a defined variable using the unset command −
unset variable_name
The above command unsets the value of a defined variable. Here is a simple example that
demonstrates how the command works −
#!/bin/sh
NAME="Zara Ali"
unset NAME
echo $NAME
The above example does not print anything. You cannot use the unset command
to unset variables that are marked readonly.
The following table shows a number of special variables that you can use in your shell scripts
1
$0 - The filename of the current script.
10 | P a g e
2
$n - These variables correspond to the arguments with which a script was invoked.
Here n is a positive decimal number corresponding to the position of an argument (the first
argument is $1, the second argument is $2, and so on).
3
$# - The number of arguments supplied to a script.
4
$* - All the arguments are double quoted. If a script receives two arguments, $* is equivalent
to $1 $2.
5
$@ - All the arguments are individually double quoted. If a script receives two arguments,
$@ is equivalent to $1 $2.
6
$? - The exit status of the last command executed.
7
$$ - The process number of the current shell. For shell scripts, this is the process ID under
which they are executing.
8
$! - The process number of the last background command.
IV Command-Line Arguments
➢ The command-line arguments $1, $2, $3, ...$9 are positional parameters, with $0
pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9
as the arguments to the command.
➢ Following script uses various special variables related to the command line −
#!/bin/sh
11 | P a g e
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
➢ Both the parameters specify the command-line arguments. However, the "$*" special
parameter takes the entire list as one argument with spaces between and the "$@"
special parameter takes the entire list and separates it into separate arguments.
➢ We can write the shell script as shown below to process an unknown number of
command line arguments with either the $* or $@ special parameters –
#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done
Here is a sample run for the above script −
$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old
Note − Here do...done is a kind of loop that will be covered in a subsequent tutorial.
VI Exit Status
• The $? variable represents the exit status of the previous command.
12 | P a g e
• Exit status is a numerical value returned by every command upon its completion. As
a rule, most commands return an exit status of 0 if they were successful, and 1 if they
were unsuccessful.
• Some commands return additional exit statuses for particular reasons. For example,
some commands differentiate between kinds of errors and will return various exit
values depending on the specific type of failure.
Shell supports a different type of variable called an array variable. This can hold multiple
values at the same time. Arrays provide a method of grouping a set of variables. Instead of
creating a new name for each variable that is required, you can use a single array variable
that stores all the other variables.
All the naming rules discussed for Shell Variables would be applicable while naming arrays.
The difference between an array variable and a scalar variable can be explained as follows.
Suppose you are trying to represent the names of various students as a set of variables. Each
of the individual variables is a scalar variable as follows –
13 | P a g e
NAME01="Zara"
NAME02="Qadir"
NAME03="Mahnaz"
NAME04="Ayan"
NAME05="Daisy"
We can use a single array to store all the above-mentioned names. Following is the simplest
method of creating an array variable. This helps assign a value to one of its indices.
array_name[index]=value
Here array_name is the name of the array, index is the index of the item in the array that you
want to set, and value is the value you want to set for that item.
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
If you are using the ksh shell, here is the syntax of array initialization −
If you are using the bash shell, here is the syntax of array initialization −
${array_name[index]}
Here array_name is the name of the array, and index is the index of the value to be accessed.
Following is an example to understand the concept −
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
14 | P a g e
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
The above example will generate the following result −
$./test.sh
First Index: Zara
Second Index: Qadir
You can access all the items in an array in one of the following ways −
${array_name[*]}
${array_name[@]}
Here array_name is the name of the array you are interested in. Following example will help
you understand the concept −
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
The above example will generate the following result −
$./test.sh
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy
• Arithmetic Operators
• Relational Operators
15 | P a g e
• Boolean Operators
• String Operators
• File Test Operators
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations
but it uses external programs, either awk or expr.
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
Total value: 4
• There must be spaces between operators and expressions. For example, 2+2 is
not correct; it should be written as 2 + 2.
• The complete expression should be enclosed between ‘ ‘, called the backtick.
a) Arithmetic Operators
+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30
- (Subtraction) Subtracts right hand operand from left hand operand `expr $a - $b` will give -10
* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give
200
16 | P a g e
/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2
% (Modulus) Divides left hand operand by right hand operand and `expr $b % $a` will give 0
returns remainder
== (Equality) Compares two numbers, if both are same then [ $a == $b ] would return
returns true. false.
!= (Not Equality) Compares two numbers, if both are different then [ $a != $b ] would return
returns true. true.
It is very important to understand that all the conditional expressions should be inside
square braces with spaces around them, for example [ $a == $b ] is correct
whereas, [$a==$b] is incorrect.
b) Relational Operators
Bourne Shell supports the following relational operators that are specific to numeric values.
These operators do not work for string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well as
in between "10" and "20" but not in between "ten" and "twenty".
-eq Checks if the value of two operands are equal or not; if yes, then [ $a -eq $b ] is not true.
the condition becomes true.
17 | P a g e
-ne Checks if the value of two operands are equal or not; if values are
[ $a -ne $b ] is true.
not equal, then the condition becomes true.
-gt Checks if the value of left operand is greater than the value of
[ $a -gt $b ] is not true.
right operand; if yes, then the condition becomes true.
-lt Checks if the value of left operand is less than the value of right
[ $a -lt $b ] is true.
operand; if yes, then the condition becomes true.
-ge Checks if the value of left operand is greater than or equal to the
[ $a -ge $b ] is not true.
value of right operand; if yes, then the condition becomes true.
-le Checks if the value of left operand is less than or equal to the
[ $a -le $b ] is true.
value of right operand; if yes, then the condition becomes true.
It is very important to understand that all the conditional expressions should be placed
inside square braces with spaces around them. For example, [ $a <= $b ] is correct
whereas, [$a <= $b] is incorrect.
c) Boolean Operators
-o This is logical OR. If one of the operands is true, then [ $a -lt 20 -o $b -gt 100 ] is true.
the condition becomes true.
d) String Operators
The following string operators are supported by Bourne Shell.
18 | P a g e
Assume variable a holds "abc" and variable b holds "efg" then −
= Checks if the value of two operands are equal or not; if [ $a = $b ] is not true.
yes, then the condition becomes true.
str Checks if str is not the empty string; if it is empty, then it [ $a ] is not false.
returns false.
19 | P a g e
I. Linux - Shell Decision Making
While writing a shell script, there may be a situation when you need to adopt one path out of
the given two paths. So, you need to make use of conditional statements that allow your
program to make correct decisions and perform the right actions.
Unix Shell supports conditional statements which are used to perform different actions
based on different conditions. We will now understand two decision-making statements
here −
• if...fi statement
• if...else...fi statement
• if...elif...else...fi statement
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false then no statement would be
executed. Most of the times, comparison operators are used for making decisions.
20 | P a g e
It is recommended to be careful with the spaces between braces and expression. No space
produces a syntax error.
If expression is a shell command, then it will be assumed true if it returns 0 after execution.
If it is a Boolean expression, then it would be true if it returns true.
Example
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
The above script will generate the following result −
a is not equal to b
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false, then no statement will be executed.
21 | P a g e
Example
The above example can also be written using the if...else statement as follows −
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
Upon execution, you will receive the following result −
a is not equal to b
Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
This code is just a series of if statements, where each if is part of the else clause of the
previous statement. Here statement(s) are executed based on the true condition, if none of
the condition is true then else block is executed.
22 | P a g e
Example
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
Upon execution, you will receive the following result −
a is less than b
Unix Shell supports case...esac statement which handles exactly this situation, and it does
so more efficiently than repeated if...elif statements.
You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.
Shell supports case...esac statement which handles exactly this situation, and it does so
more efficiently than repeated if...elif statements.
23 | P a g e
Syntax
The basic syntax of the case...esac statement is to give an expression to evaluate and to
execute several different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found.
If nothing matches, a default condition will be used.
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Here the string word is compared against every pattern until a match is found. The
statement(s) following the matching pattern executes. If no matches are found, the case
statement exits without performing any action.
When statement(s) part executes, the command ;; indicates that the program flow should
jump to the end of the entire case statement. This is similar to break in the C programming
language.
Example
#!/bin/sh
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
24 | P a g e
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
Upon execution, you will receive the following result −
A good use for a case statement is the evaluation of command line arguments as follows −
#!/bin/sh
option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac
Here is a sample run of the above program −
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$
25 | P a g e
II. Shell Loop Types
a) The while Loop
The while loop enables you to execute a set of commands repeatedly until some condition
occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
Syntax
while command
do
Statement(s) to be executed if command is true
done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are
executed. If command is false then no statement will be executed and the program will jump
to the next line after the done statement.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
Each time this loop executes, the variable a is checked to see whether it has a value that is
less than 10. If the value of a is less than 10, this test condition has an exit status of 0. In this
case, the current value of a is displayed and later a is incremented by 1.
26 | P a g e
Nesting Loops
All the loops support nesting concept which means you can put one loop inside another
similar one or different loops. This nesting can go up to unlimited number of times based on
your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the
programming requirement in a similar way −
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true
Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop
that you used to count to nine −
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
27 | P a g e
done
This will produce the following result. It is important to note how echo -n works here. Here -
n option lets echo avoid printing a new line character.
0
10
210
3210
43210
543210
6543210
76543210
876543210
9876543210
Syntax
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the variable var is
set to the next word in the list of words, word1 to wordN.
Example
Here is a simple example that uses the for loop to span through the given list of numbers −
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
Upon execution, you will receive the following result −
0
1
28 | P a g e
2
3
4
5
6
7
8
9
Following is the example to display all the files starting with .bash and available in your
home. We will execute this script from my root −
#!/bin/sh
Syntax
until command
do
Statement(s) to be executed until command is true
done
Here the Shell command is evaluated. If the resulting value is false, given statement(s) are
executed. If the command is true then no statement will be executed and the program jumps
to the next line after the done statement.
29 | P a g e
Example
Here is a simple example that uses the until loop to display the numbers zero to nine −
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
The select loop provides an easy way to create a numbered menu from which users can
select options. It is useful when you need to ask the user to choose one or more items from a
list of choices.
Syntax
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the variable var
is set to the next word in the list of words, word1 to wordN.
30 | P a g e
For every selection, a set of commands will be executed within the loop. This loop was
introduced in ksh and has been adapted into bash. It is not available in sh.
Example
Here is a simple example to let the user select a drink of choice −
#!/bin/ksh
31 | P a g e
4) juice
5) appe
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$
In this chapter, we will learn following two statements that are used to control shell loops−
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh
a=10
until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
This loop continues forever because a is always greater than or equal to 10 and it is never
less than 10.
32 | P a g e
X The break Statement
The break statement is used to terminate the execution of the entire loop, after completing
the execution of all of the lines of code up to the break statement. It then steps down to the
code following the end of the loop.
Syntax
The following break statement is used to come out of a loop −
break
The break command can also be used to exit from a nested loop using this format −
break n
Example
Here is a simple example which shows that loop terminates as soon as a becomes 5 −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
33 | P a g e
Here is a simple example of nested for loop. This script breaks out of both loops if var1
equals 2 and var2 equals 0 −
#!/bin/sh
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
Upon execution, you will receive the following result. In the inner loop, you have a break
command with the argument 2. This indicates that if a condition is met you should break out
of outer loop and ultimately from the inner loop as well.
10
15
This statement is useful when an error has occurred but you want to try to execute the next
iteration of the loop.
Syntax
continue
Like with the break statement, an integer argument can be given to the continue command
to skip commands from nested loops.
continue n
34 | P a g e
Example
The following loop makes use of the continue statement which returns from the continue
statement and starts processing the next statement −
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
35 | P a g e
I Shell Substitution
What is Substitution?
The shell performs substitution when it encounters an expression that contains one or more
special characters.
Example
Here, the printing value of the variable is substituted by its value. Same time, "\n" is
substituted by a new line −
#!/bin/sh
a=10
echo -e "Value of a is $a \n"
You will receive the following result. Here the -e option enables the interpretation of
backslash escapes.
Value of a is 10
Value of a is 10\n
1
\\ backslash
2
\a alert (BEL)
3
\b backspace
4
\c suppress trailing newline
36 | P a g e
5
\f form feed
6
\n new line
7
\r carriage return
8
\t horizontal tab
9
\v vertical tab
You can use the -E option to disable the interpretation of the backslash escapes (default).
You can use the -n option to disable the insertion of a new line.
a) Command Substitution
Command substitution is the mechanism by which the shell performs a given set of
commands and then substitutes their output in the place of the commands.
Syntax
`command`
When performing the command substitution make sure that you use the backquote, not the
single quote character.
Example
#!/bin/sh
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
37 | P a g e
UP=`date ; uptime`
echo "Uptime is $UP"
Upon execution, you will receive the following result −
Date is Thu Jul 2 03:59:57 MST 2009
Logged in user are 1
Uptime is Thu Jul 2 03:59:57 MST 2009
03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15
b) Variable Substitution
Variable substitution enables the shell programmer to manipulate the value of a variable
based on its state.
1
${var} - Substitute the value of var.
2
${var:-word} - If var is null or unset, word is substituted for var. The value of var does not
change.
3
${var:=word} - If var is null or unset, var is set to the value of word.
4
${var:?message} - If var is null or unset, message is printed to standard error. This checks
that variables are set correctly.
5
${var:+word} - If var is set, word is substituted for var. The value of var does not change.
Example
Following is the example to show various states of the above substitution −
#!/bin/sh
38 | P a g e
echo "2 - Value of var is ${var}"
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"
var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5- Value of var is Prefix
Syntax:
set [options]
o -a: It is used to mark variables that are modified or created for export.
o -b: It is used to notify of job termination immediately.
o -e: It is used to exit immediately if a command exits with a non-zero status.
39 | P a g e
o -f: It is used to disable the file name generation (globbing).
o -h: It is used to save the location of commands where they looked up.
o -k: It is used to place all assignment arguments in the environment variable of a
command, except those that precede the command name.
o -m: It is used to enable Job control.
o -n: It is used to read commands.
o -o: It is used for option-name.
o -p: It is used to disable the processing of the '$ENV' file and import shell functions. It
is turned on whenever the real and effective user ids do not match. Turning off this
option may cause the working uid and gid to be set as the authorized uid and gid.
o -t: It is used to exit from the command after executing one command.
o -u: It is used to treat unset variables as an error when substituting.
o -v: It is used to print shell input lines.
o -x: It is used to print commands and their arguments in a sequential way (as they are
executed).
o -B: It is used to perform brace expansion by the Shell.
o -C: It is used to disallow existing regular files to be overwritten by redirection of
output.
o -E: It is used if the ERR trap is inherited by the shell functions.
o -H: It is used to enable style history substitution. By default, it is on when the shell is
interactive.
o -P: It is used if we do not want to follow symbolic links when executing commands.
o -T: If this flag is set, the DEBUG trap is inherited by the shell functions.
The '-x' option is used with the set command to show command and their arguments. It is
useful for debugging the shell script.
40 | P a g e
set -x
To turn off the debugging information:
set +x
Disable Bash's default behavior.
set -C
Stop a script immediately.
set -e
III. Shift Positional Parameters
Shift is a builtin command in bash which after getting executed, shifts/move the
command line arguments to one position left. The first argument is lost after using
shift command. This command takes only one integer as an argument. This
command is useful when you want to get rid of the command line arguments which
are not needed after parsing them.
Syntax:
shift n
Example: Let’s create a shell script file named as sampleshift.sh as follows. The total
number of command-line arguments is represented by $#. Use the following
command to create the desired shell script file
vi sampleshift.sh
41 | P a g e
Now paste the following code:
#!/bin/bash
But here we have to pass command-line arguments so we can use the following
command
sh sampleshift.sh G1 G2 G3 G4
Here, we are passing 4 command-line arguments named G1, G2, G3, and G4. Below
is the screenshot of the output of using shift command:
42 | P a g e
IV. Functions
Functions enable you to break down the overall functionality of a script into smaller, logical
subsections, which can then be called upon to perform their individual tasks when needed.
Using functions to perform repetitive tasks is an excellent way to create code reuse. This is
an important part of modern object-oriented programming principles.
Shell functions are similar to subroutines, procedures, and functions in other programming
languages.
a) Creating Functions
function_name () {
list of commands
}
The name of your function is function_name, and that's what you will use to call it from
elsewhere in your scripts. The function name must be followed by parentheses, followed by
a list of commands enclosed within braces.
Example
#!/bin/sh
Following is an example where we pass two parameters Zara and Ali and then we capture
and print these parameters in the function.
#!/bin/sh
If you instead want to just terminate execution of the function, then there is way to come out
of a defined function.
Based on the situation you can return any value from your function using
the return command whose syntax is as follows −
return code
44 | P a g e
Here code can be anything you choose here, but obviously you should choose something that
is meaningful or useful in the context of your script as a whole.
Example
Following function returns a value 10 −
#!/bin/sh
d) Nested Functions
One of the more interesting features of functions is that they can call themselves and also
other functions. A function that calls itself is known as a recursive function.
#!/bin/sh
number_two () {
echo "This is now the second function speaking..."
}
You can put definitions for commonly used functions inside your .profile. These definitions
will be available whenever you log in and you can use them at the command prompt.
Alternatively, you can group the definitions in a file, say test.sh, and then execute the file in
the current shell by typing −
$. test.sh
This has the effect of causing functions defined inside test.sh to be read and defined to the
current shell as follows −
$ number_one
This is the first function speaking...
This is now the second function speaking...
$
To remove the definition of a function from the shell, use the unset command with
the .f option. This command is also used to remove the definition of a variable to the shell.
$ unset -f function_name
46 | P a g e