Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Shell Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

SHELL PROGRAMMING

The 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. A shell is an environment in which we can run our commands, programs, and
shell scripts.

Shell Prompt

The prompt, $, which is called command prompt, is issued by the shell. While the prompt
is displayed, you can type a command. The shell reads your input after you press Enter.

A simple example of date command which displays current date and time:

$date

Thu Jun 25 08:30:19 MST 2009

Shell Scripts
A set of commands that can be grouped together under a single filename and can be
executed repeatedly is called as shell scripts or shell programs. Naming a shell program has no
restriction, but the filename should end with an extension .sh .

Example for Shell Script:

# simple.sh (File Name)


# Shell script to calculate the sum of two variables # Title comment

echo –n “Enter the values of a and b:” # Output Statement


read a b # Input Statement
sum =`expr $a + $b` # Assignment Statement
echo –n “The sum of $a and $b is $sum” # Output Statement

Syntax for executing the shell program: sh filename.sh

Shell Types

In UNIX there are two major types of shells:

 The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $
character.
 The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows:

 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 AT&T Bell Labs in New Jersey.

The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as
"the shell".

Shell Keywords

Keywords also referred, as reserved words are the words whose meaning has been
already defined in the shell. Keywords cannot be used, as shell variables. All keywords must be
written in lowercase. Some keywords are

case esac if do exit read done

echo fi return until else for while

Shell Comments

Comments in shell script start with #. It can be placed anywhere in a line. Shell ignores
all characters placed on its right in that line

Example: Comments in your script as follows:

# Author : Zara Ali


# Copyright (c) Tutorialspoint.com
# Script follows here:
Pwd
ls

Shell 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.
Variable Names
Variable name is an arbitrary name used to refer to the area of memory in which a
particular value is stored.

Rules for constructing variable names:

 The first character in the variable name must be an alphabet or an underscore, and can be
followed by any number of alphabets, or digits or underscores.

 No commas or blank spaces are allowed within a variable name.

 No special character other than underscore can be used in a variable name.

 The variable name should not be a keyword.

 Variable names are case sensitive

 A variable name should not be of length more than 20 characters.

The following examples are valid variable names:

_ALI
TOKEN_A
VAR_1
VAR_2

The following examples are 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.

Defining Variables

Variables are defined as follows:

variable name=variable value

For example:

NAME="Nithya"

Above example defines the variable NAME and assigns it the value "Nithya". Variables of this
type are called scalar variables. A scalar variable can hold only one value at a time.
Accessing Values

To access the value stored in a variable, prefix its name with the dollar sign ( $).

For example, following script would access the value of defined variable NAME and
would print it on STDOUT:

NAME="Nithya"
echo $NAME

This would produce following value:

Nithya

Read-only Variables

The shell provides a way to mark variables as read-only by using the readonly command.
After a variable is marked read-only, its value cannot be changed.

For example, following script would give error while trying to change the value of NAME:

NAME="Nithya"
readonly NAME
NAME="Sri"

This would produce following result:

/bin/sh: NAME: This variable is read only.

Positional Parameters
The parameter that represents their position in the command line is known as positional
parameters.

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.

Special Variables
The following table shows a number of special variables that you can use in your shell scripts

Variable Description
$0 The filename of the current script.
These variables correspond to the arguments with which a script was
invoked. Here n is a positive decimal number corresponding to the
$n
position of an argument (the first argument is $1, the second argument
is $2, and so on).
$# The number of arguments supplied to a script.

All the arguments are double quoted. If a script receives two


$*
arguments, $* is equivalent to $1 $2.

All the arguments are individually double quoted. If a script receives


$@
two arguments, $@ is equivalent to $1 $2.

$? The exit status of the last command executed.

The process number of the current shell. For shell scripts, this is the
$$
process ID under which they are executing.

$! The process number of the last background command.

For Example, Special Parameters explained from command line statement

Simple.sh good morning nice day # command line statement

Command Output Comment


echo $0 simple.sh # Name of the command
executed
echo $1 $2 $3 $4 good morning nice day # Positional parameters

echo $# 4 # Number of arguments

echo $* good morning nice day # List of arguments


Operators in Shell
 Arithmetic Operators.
 Relational Operators.
 Boolean Operators.

Arithmetic Operators

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example


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

The expr command evaluates its arguments as arithmetic expressions and displays the result on
the standard output.

Example:

a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
echo "a is equal to b"
fi

if [ $a != $b ]
then
echo "a is not equal to b"
fi

This would produce following result:

a + b : 30
a - b : -10
a * b : 200
b/a:2
b%a:0

a is not equal to b

Relational Operators

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example


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

About Quotes

There are three types of quotes

Quotes Name Meaning


Double "Double Quotes" - Anything enclose in double quotes removed meaning of that
"
Quotes characters (except \ and $).
Single
' 'Single quotes' - Enclosed in single quotes remains unchanged.
quotes

` Back quote
`Back quote` - To execute command

Example:

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

This would produce 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

Boolean Operators

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example


This is logical negation. This inverts a
! true condition into false and vice [ ! false ] is true.
versa.
This is logical OR. If one of the
[ $a -lt 20 -o $b -gt 100 ] is
-o operands is true then condition would
true.
be true.
This is logical AND. If both the
operands are true then condition [ $a -lt 20 -a $b -gt 100 ] is
-a
would be true otherwise it would be false.
false.

Example:
a=10
b=20

if [ $a != $b ]
then
echo "$a != $b : a is not equal to b"
else
echo "$a != $b: a is equal to b"
fi

if [ $a -lt 100 -a $b -gt 15 ]


then
echo "$a -lt 100 -a $b -gt 15 : returns true"
else
echo "$a -lt 100 -a $b -gt 15 : returns false"
fi

if [ $a -lt 100 -o $b -gt 100 ]


then
echo "$a -lt 100 -o $b -gt 100 : returns true"
else
echo "$a -lt 100 -o $b -gt 100 : returns false"
fi

if [ $a -lt 5 -o $b -gt 100 ]


then
echo "$a -lt 100 -o $b -gt 100 : returns true"
else
echo "$a -lt 100 -o $b -gt 100 : returns false"

fi

This would produce following result:

10 != 20 : a is not equal to b
10 -lt 100 -a 20 -gt 15 : returns true
10 -lt 100 -o 20 -gt 100 : returns true
10 -lt 5 -o 20 -gt 100 : returns false

Decision Making

 if Statement
 if– else Statement
 if-elif-else-if Statement
 case – esac Statement

if Statement
The if...fi statement is the control statement that allows to make decisions and execute
statements conditionally.
General Format
if [ expression ]
then
Command
fi
If the resulting value is true, given statement(s) are executed. If expression is false then no
statement would be not executed.

Example:
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

This will produce following result:

a is not equal to b

if – else Statement

The if...else...fi statement is the next form of control statement that allows to execute
statements in more controlled way and making decision between two choices.

General Format

if [ expression ]
then
Command
else
Command
fi

Example:
a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi

This will produce following result:

a is not equal to b

if-elif-else-if Statement

The if...elif…else...fi statement is the next form of control statement that allows to make
correct decision out of several conditions

General Format
if [ expression 1]
then
Command
elif [ expression 2]
Command
elif [ expression 3]
Command
else
Command
fi

Here statement(s) are executed based on the true condition, if non of the condition is true
then else block is executed.

Example:

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
This will produce following result:

a is less than b

case – esac statement


The case – esac statement allows to make a decision from a number of choices.

General Format

case expression in
pattern1 )
statements
;;
pattern 2 )
Statements
;;
patternN )

*)
statements
;;
esac

Here the expression is compared against every pattern until a match is found. The statement(s)
following the matching pattern executes. The pattern labeled * is executed if none of the other
patterns are satisfied.

Example:
FRUIT="kiwi"

case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
This will produce following result:

New Zealand is famous for kiwi.

Looping Statements

A segment of the program that is executed repeatedly is called looping.

Types of looping
 For loop
 While Loop
 Until loop

The for Structure


The for statement executes depending upon the value of the argument passed in
the list specified.

General Format:
for var in num1 num2…..num N
do
commands
done
Here var is the name of a variable and num1 to num N are sequences of numbers separated by
spaces. Each time the for loop executes, the value of the variable var is set to the next number in
the list of numbers, num1 to num N.

Example:

for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var

done

This will produce following result:


0
1
2
3
4
5
6
7
8
9

While Loop Statement

The while loop enables to execute a set of commands repeatedly until some condition
occurs to false.

General format

while condition
do
commands
done
If the resulting value is true, given statement(s) are executed. If command is false then no
statement would be not executed and program would jump to the next line after done statement.

Example:

a=0

while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

This will produce following result:

0
1
2
3
4
5
6
7
8
9
Until Loop Statement:
The until loop enables to execute a set of commands until a condition is true.

General Format

until condition
do
commands

done

If the resulting value is false, given statement(s) are executed. If command is true then no
statement would be not executed and program would jump to the next line after done statement.

Example

a=0

until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

This will produce following result:

0
1
2
3
4
5
6
7
8
9

You might also like