Sunteți pe pagina 1din 8

UNIX SHELL SCRIPTING:

UNIX shell is considered as a master utility program that enables a user to gain access to all other utilities and resources
of the computer.

Shell Script
A shell script is a text file that contains a sequence of commands for a UNIX-based operating system. The shell is
the operating system's command interpreter and the set of commands you use to communicate with the system.

The most commonly used shells are SH(Bourne SHell) , CSH(C SHell) and KSH(Korn SHell), most of the other shells you
encounter will be variants of these shells and will share the same syntax.
Like: KSH & BASH(Bourne Again shell) are based on SH and TCSH Extended C Shell.

It is case sensitive

Declaration:
Declare the type of shell in order to control how the shell is going to run
eg:

#!/usr/bin/sh OR #!/bin/sh Declares a Bourne shell


#!/usr/bin/ksh OR #!/bin/ksh Declares a Korn shell
#!/usr/bin/csh OR #!/bin/csh Declares a C shell
#!/usr/bin/bash OR #!/bin/bash Declares a Bourne-Again shell

If something starts with (#) is considered as commented but if it is followed by (!) it is considered as the special and th e
path followed is the location of the shell which will interpret the script.

Eg : Shell script can be created as

$ vi test.sh
#!/bin/ksh
cd /usr/local/edw
wc -l > count
echo $count

Shell Scripting Basics:


Commands redirecting and pipelines

Redirecting
By default a normal command accepts input from standarad input and directs it to standarad output.

stdin > stdout

But we can also direct output to somewhere other than standard output.
Eg:

ls > file - It will redirect the output to a file


grep searchitem < file-It will serach for the character specified from the directed file (given after the symbol).
Date >> file it will append date value to the file
command 2> - it will redirect all errors for a executed command to a file
Pipelines

It is used to chain commands so that powerfulcomposite comands can be constructed .


the pipe symbol '|' takes the stdout from the command preceding it and redirects it to the command following it:

ls -l | grep searchword | sort r

The Evaluation of Shell Variables/Conditional Substitution


$var value of var; nothing if var undefined
${var} same; useful if alphanumerics follow
variable name
${var-str} value of var if defined; else
str; $var unchanged.
${var=str} value of var if defined; else
str; if undefined, $var set to str.
${var?str} if defined, $var; else, print
str and exit shell; if str empty, print:
var:parameter not set
${var+str} str if $var defined, else null.

Variables:

Global variables: also called environmental variables

VARIABLE_NAME=value
Export VARIABLE_NAME

EXAMPLE
PATH=/bin:/usr/bin
export PATH

Local Variables:
New variables can be instantiated like this
Variable_name=value

Variables are referenced like this: $name


name=John Doe
x=5
echo name
name
To extract the value from variables, a dollar sign is used
echo $name
John Doe
A variable may be referenced like so ${VARIABLENAME}, this allows one to place characters immediately preceding the
variable like ${VARIABLENAME}aaa without the shell interpreting aaa as being part of the variable name

The Global and Local Variables


When a variable is referenced, it is known only to the shell which created it. A new shell created by typing sh, is born
unaware of the parent shells
variables.
The same variable name (as in the parent shell) can be given a different value in the new shell. Such a variable is called
a local variable that is
known only to the child shell.
In many instances, it may be necessary for the child shell to know about the parent shells variables. They are known as
global variables.
$ city=Bombay ; echo $city # Create variable; Response: Bombay
$ sh ; echo $city # create a child shell; No response
$ city=Delhi; echo $city # Create new variable; Response: Delhi
<Press ^d> # Return to parent
echo $city # Parent continues to have value Bombay
The global variables must be exported so that the child shell is aware of them as follows:
$ export city # only the copy passed to the child

Command Line Arguments

Command line arguments are treated as special variables within the script,The command line arguments are
enumerated in the following manner $0, $1, $2, $3, $4,
$5, $6, $7, $8 and $9.

$0 is special in that it corresponds to the name of the script itself


$1 is the first argument
$2 is the second
argument and so on

Shift Command
Often used when you wish to be passwd more that 10 ($0-$9) parameters.
After the shift command is executed, the positional parameters from $2 ... are renamed $1 ...
For example, if commandfile is invoked as:
commandfile arg1 arg2 arg3 arg4 arg5 arg6
$0 $1 $2 $3 $4 $5 $6
After a shift command is executed:
commandfile arg1 arg2 arg3 arg4 arg5 arg6
$0 gone $1 $2 $3 $4 $5

eg:

cat shift.sh
echo Some
echo $1
shift
echo $1
shift
echo $1
$ ksh shift.sh were here there
were
here
there

Set commnads:
One can explicitly force values into the positional parameters using the set command.
For example set -- abc def ghi is equivalent to:
$1=abc
$2=def
$3=ghi
Note:
Positional parameters are not allowed on the left hand side of an
assignment statement.
$ vi setex
set -- THESE THREE VALUES
echo $1 $2 $3
$ sh setex
THESE THREE VALUES

Command Substitution
Command substitution allows the output of a command to be substituted in place of the command
name itself

eg: cat shift.sh


#!/bin/ksh
my_name='John'
echo `echo \ $my_name`
Output: John

Arithmetic Expansion
Arithmetic expansion is also allowed and comes in the form:
$((expression))

#!/bin/bash

first_num=0
second_num=0

echo -n "Enter the first number -->"


read first_num
echo -n "Enter the second number ->"
read second_num

echo "first number + second number = $((first_num + second_num))"


echo "first number - second number = $((first_num - second_num))"
echo "first number * second number = $((first_num * second_num))"
echo "first number / second number = $((first_num / second_num))"
echo "first number % second number = $((first_num % second_num))"

Operators:
The Bourne shell uses the built-in test command operators to test numbers and strings
Equality:
= string
!=string
eq=string
-ne=string
Relational:
-gt Greater than
-ge Greater than equal to
-lt less than
-le less than ,equal to

Logical

-a And
-o OR
! NOT

Test Command
test command is used to see if an expression is true or not

Syntax: test expression


or
[expression]

Example:$ cat > ispostive


#!/bin/sh
# Script to see whether argument is positive #
if test $1 -gt 0 then
echo "$1 number is positive"
fi
Run:$ ispostive 5
5 number is positive

Run:$ispostive -45
Nothing is printed

Control Constructs

The flow of control within SH scripts is done via four main constructs;
If
If..else
If..elif..else
Case Statement
While
Until
For..Loop

If
Syntax:
if command
then
block of statements
fi

or

if [ expression ]
then
block of statements
fi

The if construct is followed by a


command
If an expression is to be tested, it
is enclosed in square brackets
The then keyword is placed after
the closing parenthesis
An if must end with a fi

Eg: if -s $file_name
then
echo File is present
fi

If...Elif..Else
Syntax:
if [ expression ]
then
block of statements
elif [ expresssion ]
then
block of statements
else
block of statements
fi
eg:
#!/bin/sh
if [ "$1" = "1" ]
then
echo "The first choice is nice"
elif [ "$1" = "2" ]
then
echo "The second choice is just as nice"
elif [ "$1" = "3" ]
then
echo "The third choice is excellent"
else
echo "I see you were wise enough not to choose"
echo "You win"
fi

Case statement:
The case statement is terminated with esac (case backwards)
;; indicates that program flow should jump to the end of the entire case statement*) is the default
case .
Syntax:
case variable_name in
pattern1)
statements
;;
pattern2)
statements
;;
*) default value
;;
esac

eg:
case $color in
blue)
echo $color is blue
;;
green)
echo $color is green
;;
*)
echo Not a color # default
esac

Do...While

Syntax:
The Do...While takes the following generic form:

As long as the expression is true, the body of statements between do and done will be executed

while [ expression]
do
block of statements
done
eg:
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

Until:
The until loop is just like the while loop, except the body of the loop will be executed as long as the expression is false
Syntax:
until [expression]
do
block of statements
done

eg:
until test -f file
do
echo file not created yet
sleep 300;
done

For Loop:
The for loop used to iterate through a list
The for loop is followed by a variable name, the in key word, and a list of words and then a block of statements, and
terminates with the done keyword.
Syntax:
for VARIABLE in 1 2 3 4 5 .. N
do
block of statements
done

eg:
#!/bin/bash
myList=1 2 3 4 5
for i in $myList
do
echo "Welcome $i times
done