Shell Programming. Introducing UNIX Shells Shell is also a programming language and provides...

Post on 02-Jan-2016

238 views 3 download

Tags:

Transcript of Shell Programming. Introducing UNIX Shells Shell is also a programming language and provides...

Shell ProgrammingShell Programming

Introducing UNIX ShellsIntroducing UNIX Shells

Shell is also a programming language and provides various features like variables, branching, looping and so on.

The shell is a UNIX program that interprets the commands you enter from the keyboard

UNIX provides several shells, including the Bourne shell, the Korn shell, and the C shell

Steve Bourne at AT&T Bell Laboratories developed the Bourne shell as the first UNIX command processor

Introducing UNIX ShellsIntroducing UNIX Shells

The Korn shell includes many extensions, such as a history feature that lets you use a keyboard shortcut to retrieve commands you previously entered

The C shell is designed for C programmer’s use

Linux uses the freeware Bash shell as its default command interpreter

Shell Scripts

Definition : “An executable file consisting of a set of

commands to be executed is called a shell script or shell program”.

A “.sh” extension is used for shell scripts. It is not mandatory to use such extension for

shell script, but it is used to differentiate them from other files.

Shell Scripts

Shell scripts run in interpretive mode. This means that shell scripts are executed

one line at a time. They are not compile to separate

executable file as “C” programs.

When to use Shell Scripts ?

Shell scripts should be used on following occasions : While customizing a work environment. For

example, to display current date and time on log-on. Automating daily tasks. For example, to take backup

on regular intervals. Automating repetitive tasks. For example, compiling

and executing programs. Executing important system procedures. For

example, shutdown, formatting a disk.

When not to use Shell Scripts ?

Shell scripts should not be used on following occasions :

When the task to be performed is too complex.

When the task requires high degree of efficiency.

When the task requires variety of software tools.

Creating & Executing Shell Scripts

To create and execute the shell script, following the steps given below :

Open any editor like as vi, pico, emacs or any other one.

Write script instruction in a file and save the file with “.sh’ extension example, suppose the file is given name “example.sh.”

By default, any newly created file does not contain execute permissions.

Creating & Executing Shell Scripts

So allocate execution permission to the owner of a file.

For this purpose chmod command can be use as – $ chmod u+x example.sh

Invoking Scripts with sh :To use the sh command. $ sh example.sh

Making Files Executable : To make the script file an executable file.

sh Commandsh Command

The sh command invokes a new copy of the shell. You can run your script files using sh command.

sh Commandsh Command

Options of sh Command-n : Read commands, but does not execute them.

-v : Prints the input to the shell as the shell reads it.-x : Prints command lines and their arguments as they are executed. This option is used mostly for debugging.

Accepting Inputs

There are two methods available to accept input from users.

These methods are as follows: Interactive Method Non-Interactive Method

Interactive Method

It uses read command to read input values in variables.

The syntax of read command is:

Read variable_name When script encounters this command, it pauses

at that point to take input from the keyboard. Any value entered by the user is stored in the

variable specified with the read command.

Non-Interactive Method

It is uses command line arguments. User can provide arguments as the command

prompt while executing the shell script. Such arguments can be provided along with

the script name. For example, following copyfile program

takes two argument as file names

$ copyfile source.txt dest.txt

Non-Interactive Method

When arguments are specified with a shell script, they are assigned to certain special variable called positional parameters.

The first argument is read by the shell into the parameter $1 and the second in $2 and so on.

In our example, $1 contains source.txt while $2 contains dest.txt.

Non-Interactive Method

Along with these positional parameters, there are a few other special parameters used by the shell.

They are given as below; $0 : holds the command name (or program

name) itself. $* : holds the complete set of positional

parameters as a single string. In our example, it contains ‘source.txt, dest.txt’

Non-Interactive Method

$# : holds the number of arguments specified in command line. In our example, it holds 2.

$? : holds the exit status of last command. (if exit status is 0, successful, else failure.)

$$ : holds the process ID(PID) of the current shell.

$! : holds the PID of the last background process.

Evaluate Expressions using ‘test’ & […]

The test & […] commands are used to evaluate conditional expressions with integers, strings and file attributes.

The syntax of test commands is: test expression

The syntax of […] commands is:[expression]

Here, expression is the conditions to be evaluated.This expression must be enclosed by white spaces before and after it.

Evaluate Expressions using ‘test’ & […]

White space must also separate the expression argument the expression arguments and operators.

It the expression evaluates to true, then a zero exit status is returned, otherwise the expression evaluates to false and a non-zero exit status is returned.

The various operators that can be used with both of these commands.

Integer Related OperatorExpression Result

exp1 –eq exp2 True if exp1 is equal to exp2

exp1 –ne exp2 True if exp1 is not equal to exp2

exp1 –le exp2 True if exp1 is less than or equal to exp2

exp1 –lt exp2 True if exp1 is less than exp2

exp1 –ge exp2 True if exp1 is greater than or equal to exp2

exp1 –gt exp2 True if exp1 is greater exp2

File Related OperatorExpression Result

-b file True if file exists & is a block special file

-c file True if file exists & is a character special file

-d file True if file exists & is a directory

-f file True if file exists & is a regular file

-r file True if file exists & is readable

-w file True if file exists & is a writable

File Related OperatorExpression Result

-x file True if file exists & is executable

-k file True if file exists & is sticky bit is set

-L file True if file exists & is a symbolic link

-s file True if file exists & its size is grater than zero

f1 -nt f2 True if f1 is newer than f2 (supported by korn and bash shell only)

f1 -ot f2 True if f1 is newer than f2 (supported by korn and bash shell only)

f1 -ef f2 True if f1 is newer than f2 (supported by korn and bash shell only)

String Related OperatorExpression Result

-n string True if length of string is not zero

-z string True if length of string is zero

String True if string of string is not set to null

string1 = string2 True if string1 is equal to string2

String Related test OperatorExpression Result

string1 != string2 True if string1 is not equal to string2

string = pattern True if string is matches pattern

string != pattern True if string does not match pattern

Other Operator

Expression Result

!exp True if the given expression is false

\(exp\) True if exp is true; used to group expressions

exp1 –a exp2 True if both exp1 and exp2 evaluate to true (AND operation)

exp1 –o exp2 True if either exp1 and exp2 evaluate to true (OR operation)

Branching

The shell support various programming constructs to provide branching functionality.

This include simple if, if..else, else-if ladder and case statement.

Simple if Syntax :

if command1then

commandsfi

Usage : execute commands if command1 remains successful.

Example :if cp source.txt dest.txt

thenecho “file copied successfully….”

fi

if…else Syntax :

if command1then

command2else command3fi

Usage : execute command2 if command1 remains successful, otherwise execute command3.

if…else Example :

if cp source.txt dest.txtthen

echo “file copied successfully….”

elseecho “some problem in copy

operation”fi

else…if ladder Syntax :

if command1then

commandelif command2then

commandelif command-nthen commandselse

commandsfi

else…if ladder Usage : whenever any command remains

successful either with if or with elif, execute the commands associated with that block.

When all the ‘n’ commands remained unsuccessful, then final commands associated with else will be executed.

Case Syntax :

case expression inpattern1)

command1;;pattern2)

command2;;pattern3)

command3;;…

patternn) commandn;;

esac

Case

Usage : execute commands associated with the pattern that matches expression.

Multiple patterns can be given but must be separated with a | character.

Each command list is terminated with a pair of semicolons, and the entire construct is closed with esac (reverse of case)

Case

Example :

echo “Do u like shell-programming? (y/n)”

read answer

case $answer in

y|Y) echo “wow…! It’s good!”;;

n|N) echo “U should like it. It’s important for exams”;;

esac

expr Command Syntax : expr expression Usage : evaluates the given mathematical

expression. Options : expression can be of the form :

expr1 operator expr2 Here, operator can be +(plus), -(minus), \

*(multiplication), /(division) or %(modulo). Also, operator must be enclosed by white

space on either side of it. Examples :

- expr 5 + 3 - expr $x \* $y

Looping

The shell supports various programming constructs to provide looping functionality.

This includes : while until for

While

Syntax :

while command1

do

commands

done

Usage : execute commands while command1 remains successful.

While Example :

echo “enter no:”read noi=1

while [ $i –le $no ]do

echo “$i”i=`expr $i + 1` #not ‘ ‘ but ` `

done

until

Syntax :

until command1

do

commands

done

Usage : execute commands while command1 remains UN-successful.

until Example :

echo “enter no:”read noi=1

until [ $i –gt $no ]do

echo “$i’i=`expr $i + 1`

done

for Syntax :

for variable in list of argumentdo

commandsdone

Usage : here, list contains white space separated words, such as-

test1 test2 test3 test4 Commands are executed until list is exhausted. Each time single word is assigned to variable

during loop execution.

for Example :

for i in 1 2 3 4 5do

echo “$i’done