Shell Script Basics
Shell Script Basics
Aim:
Theory:
A Shell provides you with an interface to the Unix system. It gathers input from you and executes
programs based on that input. When a program finishes executing, it displays that program's output.
Shell is an environment in which we can run our commands, programs, and shell scripts. There are
different flavors of a shell, just as there are different flavors of operating systems. Each flavor of
shell has its own set of recognized commands and functions.
Shell Prompt
The prompt, $, which is called the command prompt, is issued by the shell. While the prompt is
displayed, you can type a command.
Shell reads your input after you press Enter. It determines the command you want executed by
looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs
separate words.
Following is a simple example of the date command, which displays the current date and time −
$date
Tue Jan 9 14:25:11 IST 2018
Shell Types
In Unix, there are two major types of shells −
• Bourne shell − If you are using a Bourne-type shell, the $ character is the default prompt.
• C shell − If you are using a C-type shell, the % character is the default prompt.
Shell Scripts
The basic concept of a shell script is a list of commands, which are listed in the order of execution.
A good shell script will have comments, preceded by # sign, describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing us to go through
massive amounts of data, files to read and store data, and variables to read and store data, and the
script may include functions.
We are going to write many scripts in the next sections. It would be a simple text file in which we
would put all our commands and several other required constructs that tell the shell environment
what to do and when to do it.
Shell scripts and functions are both interpreted. This means they are not compiled.
Example Script
Assume we create a test.sh script. Note all the scripts would have the .sh extension. Before you add
anything else to your script, you need to alert the system that a shell script is being started. This is
done using the shebang construct. For example −
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne shell. It's
called a shebang because the # symbol is called a hash, and the ! symbol is called a bang.
To create a script containing these commands, you put the shebang line first and then add the
commands −
#!/bin/bash
pwd
ls
Shell Comments
You can put your comments in your script as follows −
#!/bin/sh
pwd
ls
Save the above content and make the script executable −
chmod +x test.sh
$ vi expt2.sh
#!/bin/sh
# Author :Sonali Bodekar-Kale
# Script follows here:
$ vi expt2.sh
$ chmod +x expt2.sh
$ ./expt2.sh
What is your name?
Sonali
Hello, Sonali
$
NAME
echo - display a line of text.
EXAMPLES
Example-1:
To print string "Hello, World!" on console
$ echo "Hello, World!"
output:
Hello, World!
Example-2:
To print value of x, where x=10.
$ echo $x
output:
10
Unix / Linux - Shell Basic Operators
There are various operators supported by each shell. We will discuss in detail about Bourne shell
(default shell)..
We will now discuss the following operators −
• Arithmetic Operators
• Relational Operators
• 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.
The following example shows how to add two numbers −
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
Arithmetic Operators
The following arithmetic operators are supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
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.
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
~
~
~
~
~
~
~
"program1.sh" 8 lines, 62 characters
$ vi program1.sh
$ chmod +x program1.sh
$ ./program1.sh
a + b : 30
Shell Relational Operators Example
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.
Assume variable a holds 10 and variable b holds 20 then −
Example
Here is an example which uses all the relational operators −
#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
echo "$a -eq $b : a is equal to b"
else
echo "$a -eq $b: a is not equal to b"
fi
if [ $a -ne $b ]
then
echo "$a -ne $b: a is not equal to b"
else
echo "$a -ne $b : a is equal to b"
fi
if [ $a -gt $b ]
then
echo "$a -gt $b: a is greater than b"
else
echo "$a -gt $b: a is not greater than b"
fi
if [ $a -lt $b ]
then
echo "$a -lt $b: a is less than b"
else
echo "$a -lt $b: a is not less than b"
fi
if [ $a -ge $b ]
then
echo "$a -ge $b: a is greater or equal to b"
else
echo "$a -ge $b: a is not greater or equal to b"
fi
if [ $a -le $b ]
then
echo "$a -le $b: a is less or equal to b"
else
echo "$a -le $b: a is not less or equal to b"
fi
The following points need to be considered while working with relational operators −
• There must be spaces between the operators and the expressions. For example, 2+2 is not
correct; it should be written as 2 + 2.
• if...then...else...fi statement is a decision-making statement which has been explained as
follows:
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 −
• The if...else statement
You will use different loops based on the situation. For example, the while loop executes the given
commands until the given condition remains true; the until loop executes until a given condition
becomes true.
Once you have good programming practice you will gain the expertise and thereby, start using
appropriate loop based on the situation. Here, while and for loops are available in most of the other
programming languages like C, C++ and PERL, etc.
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 −
Nesting while Loops
It is possible to use a while loop as part of the body of another while loop.
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`
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
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0
Now, we will discuss shell loop control in Unix. So far you have looked at creating loops and
working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip
iterations of the loop.
We will learn following two statements that are used to control shell loops−
• The break statement
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.
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
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.
1 0
1 5
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
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"
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
Here are following escape sequences which can be used in echo command −
\a
2
alert (BEL)
\b
3
backspace
\c
4
suppress trailing newline
\f
5
form feed
\n
6
new line
\r
7
carriage return
\t
8
horizontal tab
\v
9
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.
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
The command substitution is performed when a command is given as −
`command`
When performing the command substitution make sure that you use the backquote, not the single
quote character.
Example
Command substitution is generally used to assign the output of a command to a variable. Each of
the following examples demonstrates the command substitution −
#!/bin/sh
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"
Conclusion: