0% found this document useful (0 votes)
48 views

Shell Script Basics

Shell provides an interface to interact with the Unix system. It executes commands and displays outputs. There are different shell types like Bourne shell and C shell with different prompts. Shell scripts allow automation through a list of commands. Common shell commands include echo to display text and read to take user input. Operators allow for arithmetic, relational, boolean, and string operations in shell scripts.

Uploaded by

abhya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Shell Script Basics

Shell provides an interface to interact with the Unix system. It executes commands and displays outputs. There are different shell types like Bourne shell and C shell with different prompts. Shell scripts allow automation through a list of commands. Common shell commands include echo to display text and read to take user input. Operators allow for arithmetic, relational, boolean, and string operations in shell scripts.

Uploaded by

abhya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

EXPERIMENT NO.

Aim:

Theory:

Unix / Linux - What is Shells?

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.

The Bourne Shell has the following subcategories −


• Bourne shell (sh)
• Korn shell (ksh)
• Bourne Again shell (bash)
• POSIX shell (sh)

The different C-type shells follow −


• C shell (csh)
• TENEX/TOPS C shell (tcsh)
The original Unix shell was written in the mid-1970s by Stephen R. Bourne while he was at the
AT&T Bell Labs in New Jersey.
Bourne shell was the first shell to appear on Unix systems, thus it is referred to as "the shell".
Bourne shell is usually installed as /bin/sh on most versions of Unix. For this reason, it is the shell
of choice for writing scripts that can be used on different versions of Unix.
In this , we are going to cover most of the Shell concepts that are based on the Borne Shell.

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

# Author :Sonali Bodekar-Kale


# Script follows here:

pwd
ls
Save the above content and make the script executable −
chmod +x test.sh

The shell script is now ready to be executed −


$./test.sh

Upon execution, you will receive the following result −


/home/sonali
a.out Public
Cloud Computing lab-Practical list.pdf Screenshot from 2017-09-14 08-53-
24.png
copyfile Screenshot from 2017-09-14 08-53-24.xcf
cst2 sonal
Desktop sonu
Documents sovira
Downloads sovira.sh
DSFP Syllabus.odt Templates
examples.desktop test.sh
expt2.sh Turbo C++ 3.2.zip
ira UMIT_Sonali
linkedList.c Untitled 1.odt
Music Videos
Pictures Vi editor tutorial.odt

Note − To execute a program available in the current directory, use ./program_name

Extended Shell Scripts


Shell scripts have several required constructs that tell the shell environment what to do and when to
do it. Of course, most scripts are more complex than the above one.
The shell is, after all, a real programming language, complete with variables, control structures, and
so forth. No matter how complicated a script gets, it is still just a list of commands executed
sequentially.
The following script uses the read command which takes the input from the keyboard and assigns it
as the value of the variable PERSON and finally prints it on STDOUT.

$ vi expt2.sh

#!/bin/sh
# Author :Sonali Bodekar-Kale
# Script follows here:

echo "What is your name?"


read PERSON
echo "Hello, $PERSON"
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
"expt2.sh" 7 lines, 124 characters

Here is a sample run of the script −

$ vi expt2.sh
$ chmod +x expt2.sh
$ ./expt2.sh
What is your name?
Sonali
Hello, Sonali
$

echo- Unix, Linux Command

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"

The above script will generate the following result −


Total value : 4

The following points need to be considered while adding −


• 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.

Arithmetic Operators
The following arithmetic operators are supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example


+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30
Subtracts right hand operand from left hand
- (Subtraction) `expr $a - $b` will give -10
operand
* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give 200
/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2
Divides left hand operand by right hand operand
% (Modulus) `expr $b % $a` will give 0
and returns remainder
a = $b would assign value
= (Assignment) Assigns right operand in left operand
of b into a
Compares two numbers, if both are same then [ $a == $b ] would return
== (Equality)
returns true. false.
Compares two numbers, if both are different then [ $a != $b ] would return
!= (Not Equality)
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.

Sample program for addition operator:


#!/bin/sh

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"
~
~
~
~
~
~
~
"program1.sh" 8 lines, 62 characters

Here is a sample run of the script −

$ 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 −

Operator Description Example


Checks if the value of two operands are equal or not; if yes, then the [ $a -eq $b ] is
-eq
condition becomes true. not true.
Checks if the value of two operands are equal or not; if values are not [ $a -ne $b ] is
-ne
equal, then the condition becomes true. true.
Checks if the value of left operand is greater than the value of right [ $a -gt $b ] is
-gt
operand; if yes, then the condition becomes true. not true.
Checks if the value of left operand is less than the value of right [ $a -lt $b ] is
-lt
operand; if yes, then the condition becomes true. true.
Checks if the value of left operand is greater than or equal to the value [ $a -ge $b ] is
-ge
of right operand; if yes, then the condition becomes true. not true.
Checks if the value of left operand is less than or equal to the value of [ $a -le $b ] is
-le
right operand; if yes, then the condition becomes true. 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.

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 above script will generate the following result −


10 -eq 20: a is not equal to b
10 -ne 20: a is not equal to b
10 -gt 20: a is not greater than b
10 -lt 20: a is less than b
10 -ge 20: a is not greater or equal to b
10 -le 20: a is less or equal to b

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

The if...else statements


If else statements are useful decision-making statements which can be used to select an option from
a given set of options.
Unix Shell supports following forms of if…else statement −
• if...fi statement
• if...else...fi statement
• if...elif...else...fi statement

The syntax of the if else statement is:


if [ expr ]
then
//expression to be evaluated
else
//expression to be evaluated
fi
Every ‘if’ statement should be end by ‘end fi’ statement.In the expr of if statement if we need to
compare the two numbers we use the following codes:
1. For equal to: -eq
2. For less-than:-lt
3. For greater than:-gt
4. For less than or equal to:-le
5. For greater than or equal to:-ge

Shell loops in Unix


A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In
this chapter, we will examine the following types of loops available to shell programmers −
• The while loop
• The for loop
• The until loop
• The select loop

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

while command2 ; # this is loop2, the inner loop


do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true


done

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

• The continue statement

The infinite Loop


All the loops have a limited life and they come out once the condition is false or true depending on
the loop.
A loop may continue forever if the required condition is not met. A loop that executes forever
without terminating executes for an infinite number of times. For this reason, such loops are called
infinite 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.

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

Here n specifies the nth enclosing loop to the exit from.

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

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

The continue statement


The continue statement is similar to the break command, except that it causes the current iteration
of the loop to exit, rather than the entire loop.
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

Here n specifies the nth enclosing loop to continue from.

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"

for NUM in $NUMS


do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done

Upon execution, you will receive the following result −


Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number

Unix / Linux - Shell 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

Following is the result without -e option −


Value of a is 10\n

Here are following escape sequences which can be used in echo command −

S.No. Escape & Description


\\
1
backslash

\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"

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

Conclusion:

You might also like