Unix Shell Programming

67
UNIX Shell Scripting Line Segments is Our Line Segments is Our Thoughts Thoughts To Scribble on Unix…” To Scribble on Unix…”

Transcript of Unix Shell Programming

Page 1: Unix Shell Programming

UNIX Shell Scripting

“ “Line Segments is OurLine Segments is OurThoughts Thoughts

To Scribble on Unix…”To Scribble on Unix…”

Page 2: Unix Shell Programming

04/08/23

204/08/23Confidential © Tech Mahindra 2006

Session Plan

• Shell Programming• Introduction • Uses of Shell Scripts• Variables

Types of Variables, Rules, Assignment Operations

• Type Conversions (String to Integer & Float)

• Statements Non - Executable and Executable

• Positional Parameters

• Signals and Trap

Page 3: Unix Shell Programming

04/08/23

304/08/23Confidential © Tech Mahindra 2006

What is Shell Programming ?It is a series of user commands that can be done in a

sequential manner, that carries out an entire procedure. Such programs are

known as Shell Scripts.

There are around 280 shell scripts that comes with the Unix Operating System

Note :1. Shell program written in Bourne shell are likely to work

with Korn shell but the reverse is not true.2. Scripts written for one shell may not work with the other

shell

Introduction (Contd.)

Page 4: Unix Shell Programming

04/08/23

404/08/23Confidential © Tech Mahindra 2006

Uses of Shell Script

Customizing your work environmentEg.: When you log in if you want to see the current

date, time and welcome message.

Automating your daily tasks.Eg.: For back up all programs everyday at evening

time. Automating repetitive tasks.

Eg.: Producing sales report every month. Performing same operation on many files

Eg.: Converting cerr to cout in all .cc files

Page 5: Unix Shell Programming

04/08/23

504/08/23Confidential © Tech Mahindra 2006

Variables

The Value which is going to have change in nature is known as

variable.

Types of Variables

Shell Variables

System Variables User-defined variables

Page 6: Unix Shell Programming

04/08/23

604/08/23Confidential © Tech Mahindra 2006

Variables (Contd.)

System VariablesThese Variables can be accessed anywhere from the shell.

The following table shows some of the system variables.

Variable Meaning

PS2 System prompt 2, (By default value is “>”)

PATH Defines the path which the shell must search in order to execute any command or file.

HOME Stores the default working directory of the user

LOGNAME Stores the login name of the user

MAIL Defines the file where the mail of the user is stored.

Page 7: Unix Shell Programming

04/08/23

704/08/23Confidential © Tech Mahindra 2006

Variables (Contd.)

System Variables (Contd…)Variable Meaning

IFS Defines Internal Field Separator, which is a space, a tab or a newline (By default the value is space). Eg.: echo $IFS

SHELL Defines the name of your default working shell. Eg.: echo $SHELL

TERM Defines the name of the terminal on which we are working. Eg.: echo $TERM

TZ Defines the name of the time zone on which you are working.

Page 8: Unix Shell Programming

04/08/23

804/08/23Confidential © Tech Mahindra 2006

User Defined VariablesThese are all defined by the user either in the

shell prompt or in the shell script.

Rules Variable can be any combination of alphabets, digits and

underscore No commas or blanks are allowed within the variable First character must be either an alphabet or

underscore User defined variable name can be of any length User defined variable is case sensitive (i.e., bms, Bms,

BMS are all different variables)

Keywords cannot be used as variable names

Variables (Contd.)

Page 9: Unix Shell Programming

04/08/23

904/08/23Confidential © Tech Mahindra 2006

Note :1. By default the values assigned to the variables in

Shell Prog. will be considered as String values. 2. User defined variables will have their scope till the

execution of the script. 3. In Shell programming there is no need to declare

the variables as in C language. 4. While assigning more than one value to a variable it

has to be enclosed within quotes (either using “ or ‘). 5. Printing a null variable, only blank line appears on

the screen. 6. No spaces should be given before and after = while assigning a value. 7. Can have more than one assignment in a line.

Variables (Contd.)

Page 10: Unix Shell Programming

04/08/23

1004/08/23Confidential © Tech Mahindra 2006

Eg.:a. var=20

Assigns a value 20 to the user defined variable var.

b. name=bms perc=75 Assigns a value bms and 75 to the variable named

name and perc respectively. While assigning a value to more than one variable in a line it has be separated by a delimiter (i.e., space)

c. name=“bms” (or) name=‘bms’ (or) name=bmsAll remains the same. If we are assigning only one

word to the variable the quotes are optional.

d. coll=“Jyoti Nivas” (or) coll=‘Jyoti Nivas’While assigning more than one word to the

variable, it has to be represented by quotes either using “ or ‘

Variables (Contd.)

Page 11: Unix Shell Programming

04/08/23

1104/08/23Confidential © Tech Mahindra 2006

Eg.:e. spa= “ “ (or) spa=‘ ‘ (or) spa=

Assigns a null value to the variable named spa. While printing a variable without any value. The shell will print a Blank Line.

f. rd=‘welcome to shell programming’ readonly rd

The variable rd becomes a read only variable. (i.e., We cannot change the value of the read only variable named rd till the end of the script).

g. rd=‘welcome to shell programming’ echo $rd

unset rd echo $rd

First echo statement will print the value of the variable rd. The unset command is used to remove the variable rd from the memory and the second echo statement will print a blank line

Variables (Contd.)

Page 12: Unix Shell Programming

04/08/23

1204/08/23Confidential © Tech Mahindra 2006

Type ConversionInitially the values assigned to the variable in Unix will

be treated as a string value. We cannot perform any Arithmetic & Relational operators operation.

1. Converting String Value to Integer ValueTo convert the string value to an integer value

in Unix we use the command expr preceded by the variables and enclosed within Accent Graves (or) Reverse Quotes denoted by ` .

Syntax : `expr $<variable> <operator> $<variable>`

Eg.: `expr $a + $b`

Variables (Contd.)

Page 13: Unix Shell Programming

04/08/23

1304/08/23Confidential © Tech Mahindra 2006

2. Converting String Value to Float ValueTo convert the string value to an float value in

Unix we use the command bc (Byte Calculation or Bench Calculator) followed by the variables and pipe sign.

The bc command has to be used along with the echo command.

Syntax : `echo $<variable> <operator> $<variable>|bc`

Eg.:` echo $a / $b|bc -l`

Variables (Contd.)

Page 14: Unix Shell Programming

04/08/23

1404/08/23Confidential © Tech Mahindra 2006

Operators Arithmetic Operators

+ , - : For Addition & Subtraction\* , “ * “ : For Multiplication/ (Front Slash) : For Division% : For Modular Division (To Find the

Remainder)

Relation Operators-lt : Less Than -gt : Greater Than-le : Less than or equal to -ge : Greater Than or Equal to-eq : Equal to -ne : Not Equal to

Logical Operators-a : AND Gate Operation -o : OR Gate

Operation! : NOT Gate Operation

Page 15: Unix Shell Programming

04/08/23

1504/08/23Confidential © Tech Mahindra 2006

Test Conditions

There are 3 different types of test conditions are available, they

area. Numerical Testb. String Testc. File Test

Test conditions will be used only in conditional and looping

statements. Keyword : [ … ] or test Syntax :

a. [ <Condition> ]b. test <condition>

Page 16: Unix Shell Programming

04/08/23

1604/08/23Confidential © Tech Mahindra 2006

Test Conditions (Contd.)

a. Numerical TestThis can be used with relational and logical

operators. Used to check for numeric values.

b. String Test Used to check for string values

Condition Meaning

str1 = str2 True if the strings are same

str1 != str2 True if the strings are different

-n str True if the length of the string is > 0

-z str True if the length of the string = 0

str True if the string is not a null string, Same as –n str.

Page 17: Unix Shell Programming

04/08/23

1704/08/23Confidential © Tech Mahindra 2006

Test Conditions (Contd.)

c. File TestThis is used to check for the status of the file.

Option Meaning

-s file True if the file exists and has a size > 0

-f file True if the given name is a file

-d file True if the given name is a directory

-r file True if the given name has a read permission

-w file True if the given name has a write permission

-x file True if the given name has a execute permission

Page 18: Unix Shell Programming

04/08/23

1804/08/23Confidential © Tech Mahindra 2006

Statements

An Instruction with proper syntax and semantics is known as statement. Types of Statement

There are 2 types of statement they are Non-Executable and Executable Statements.

a. Non – Executable StatementIt is other wise known as Remarkable or Comment statement. Which will never get executed by the command interpreter, its only for the user reference. The Line preceded by # symbol will be considered as Non – Executable statement in UnixEg.: i. # Program For Factorial of the given number ii. a=`expr $a + $b` # Expr is used to convert string to integer

Page 19: Unix Shell Programming

04/08/23

1904/08/23Confidential © Tech Mahindra 2006

b. Executable StatementsWhich are interpreted and executed by the

command interpreter.There are various types of executable statements they

are

Input and Output Conditional Multiple Conditional Looping

Statements (Contd.)

Page 20: Unix Shell Programming

04/08/23

2004/08/23Confidential © Tech Mahindra 2006

a. Input and Output StatementIt is used to take the input and to display the output

on the standard input and output device. (i.e., Keyboard & Monitor).

Keyword : read (used for Input Statement) echo (used for Output Statement)

Syntax : a. read <variable name> b. echo $<variable name> c. echo <comments> d. echo <comments> $<variable

name> e. echo ${<variable name>-<value>}

(If we give + sign it will assign a null value to the

variable name specified).

Statements (Contd.)

Page 21: Unix Shell Programming

04/08/23

2104/08/23Confidential © Tech Mahindra 2006

Eg.:a. read namUsed to take the input for the variable nam during the runtimeb. read nam nam1 nam2 The input values for the above variables has to be separated by a space. (i.e., mag bms balaji , now nam = mag , nam1 = bms, nam2 = balaji).c. echo $aPrints the value of the variable named a. To print the values of the variables it has to be preceded by $ sign.d. echo Value of A = $a (or) echo “ Value of A = “$aPrints the value of a along with the comment line mentioned. The comments in echo can be either placed within or without quotes.

Statements (Contd.)

Page 22: Unix Shell Programming

04/08/23

2204/08/23Confidential © Tech Mahindra 2006

Eg.:e. echo ${fav-Jyoti Nivas}

The above command assigns the value Jyoti Nivas to the variable fav.

f. echo ${fav1+christ} Since we have a + sign within the flower braces.

The command interpreter will assign a value null to the variable named fav1. g. echo –n “ Enter Your Choice “

Places the cursor position on the same line after printing the statement “ Enter Your Choice “h. echo `date`

Used to display the system date on the standard output device i.e., monitor. (To execute any built in commands using echo keyword it has to be enclosed within ascent graves).

Statements (Contd.)

Page 23: Unix Shell Programming

04/08/23

2304/08/23Confidential © Tech Mahindra 2006

Eg.:i. echo *

Used to list all the files in the current working directory.j. echo \*

Used to display the * on the standard output device monitor.

k. echo a + bUsed to display the word a + b on the standard

output device.l. echo `a + b` (Placed in Ascent Graves)

Display an error message.

Statements (Contd.)

Page 24: Unix Shell Programming

04/08/23

2404/08/23Confidential © Tech Mahindra 2006

b. Conditional StatementUsed to check the condition before executing the

statements. It can have minimum one branch and maximum two branches

for a single condition. There are different types of conditional

statements, they are

i. Simple ifii. if … elseiii. Nested if … elseiv. elif ladder

Statements (Contd.)

Page 25: Unix Shell Programming

04/08/23

2504/08/23Confidential © Tech Mahindra 2006

i. Simple if :Provides a single branch for a condition.

Keyword : if , then , fiSyntax :

Statements (Contd.)

a. if [ condition ]

then

st1

fi

b. if test <condition>

then

st1

fi

a. if [ condition ]

then

st1

fi

b. if test <condition>

then

st1

fi

Page 26: Unix Shell Programming

04/08/23

2604/08/23Confidential © Tech Mahindra 2006

Statements (Contd.)

Eg.: Without Using test K/w.

echo “ Enter The Value of A & B “

read a

read b

if [ $a –gt $b ]

then

echo “ A is greater “

fi

Eg.: Using test K/w.

echo “ Enter The Value of A & B “

read a

read b

if test $a –gt $b

then

echo “ A is greater “

fi

Page 27: Unix Shell Programming

04/08/23

2704/08/23Confidential © Tech Mahindra 2006

ii. if … elseProvides two branches for a condition.

Keyword : if , then , else , fiSyntax :

Statements (Contd.)

a. if [ condition ]

then

st1

else

st2

fi

b. if test <condition>

then

st1

else

st2

fi

Page 28: Unix Shell Programming

04/08/23

2804/08/23Confidential © Tech Mahindra 2006

Statements (Contd.)

Eg.: Without Using test K/w.

echo “ Enter The Value of A & B “

read a

read b

if [ $a –gt $b ]

then

echo “ A is greater “

else

echo “ B is greater “

fi

Eg.: Using test K/w.

echo “ Enter The Value of A & B “

read a

read b

if test $a –gt $b

then

echo “ A is greater “

else

echo “ B is greater “

fi

Page 29: Unix Shell Programming

04/08/23

2904/08/23Confidential © Tech Mahindra 2006

iii. Nested if … elseSyntax :

Statements (Contd.)

a. if [ condition1 ]

then

if [ condition1 ]

st1

else

st2

fi

else

st2

fi

b. if test condition1

then

if test condition1

then

st1

else

st2

fi

else

st2

fi

Page 30: Unix Shell Programming

04/08/23

3004/08/23Confidential © Tech Mahindra 2006

iii. elif ladderSyntax :

Statements (Contd.)

a. if [ condition1 ]

then

st1

elif [ condition2 ]

then

st2

elif [ condition3]

then

st3

fi

b. if test condition1

then

st1

elif test condition2

then

st2

elif test condition3

then

st3

fi

Page 31: Unix Shell Programming

04/08/23

3104/08/23Confidential © Tech Mahindra 2006

Statements (Contd.)

What is the difference between nested if … else and elif ladder

statements in Unix ?

Nested if elif ladder

In the case of Nested if statement we need to end it with fi for each and every if statement.

In the case of elif ladder we need to have only one fi statement irrespective of the number of if statements we have used.

Page 32: Unix Shell Programming

04/08/23

3204/08/23Confidential © Tech Mahindra 2006

c. Multiple Conditional StatementsIt is similar to that of switch statements in C.

We will be using this provided when we have more than 2 branches for a single condition.

Keyword : case , esac Syntax : case $<variable> in

<value1>) st1 ;;

<value2>) st2 ;;

*) st3 ;;

esacNote : Each and every case has to be ended

with ;; , It is similar to that of break statements in C

language.

Statements (Contd.)

Similar to default block in C

Page 33: Unix Shell Programming

04/08/23

3304/08/23Confidential © Tech Mahindra 2006

Eg.: echo “ Main Menu “ echo “ 1. Addition “ echo “ 2. Subtraction “ echo “ 3. Multiplication” echo “ 4. Exit “ echo “ Enter Your Choice “ read ch case $ch in 1) c=`expr 10 + 20` ;; 2) c = `expr 10 – 20`;; 3) c = `expr 10 \* 20`;; *) echo “ Enter Proper Value “;; esac echo “ Value of C = “ $c

Statements (Contd.)

I/p : 1

O/p: Value of C = 30

Page 34: Unix Shell Programming

04/08/23

3404/08/23Confidential © Tech Mahindra 2006

Eg.: 2. # Program to check whether the entered input is a lower case , upper case alphabet or a digit.

echo “ Enter The Value “ read ch case $ch in [a-z]) echo “ Entered Lower Case Letters “ ;;

[A-Z]) echo “ Entered Upper Case Letters “;; [0-9]) echo “ Entered Numbers”;;

*) echo “ Special Characters “;;esac

Statements (Contd.)

Page 35: Unix Shell Programming

04/08/23

3504/08/23Confidential © Tech Mahindra 2006

Eg.: 3. # Program to check whether the entered number from 1 to 10 is even or odd

echo “ Enter The Numbers between 1 to 10 “ read ch case $ch in 1|3|5|7|9) echo “ Odd Numbers “ ;;

2|4|6|8|10) echo “ Even Numbers “;; *) echo “ Invalid Input “;;

esac

Statements (Contd.)

Page 36: Unix Shell Programming

04/08/23

3604/08/23Confidential © Tech Mahindra 2006

d. Looping StatementUsed to perform the same set of operations for

more than one time till the specified condition is true or false. There are 3 types of looping statements, they are

i. whileii. untiliii. for

The first two are used for numerical operations. The final one is used for string manipulation, used to generate the tokens separately.

Statements (Contd.)

Page 37: Unix Shell Programming

04/08/23

3704/08/23Confidential © Tech Mahindra 2006

i. while :This will execute the set of statements repeatedly

until the specified condition is true

Syntax :

Statements (Contd.)

a. while [ <condition> ]

do

statements

done

b. while test <condition>

do

statements

done

Page 38: Unix Shell Programming

04/08/23

3804/08/23Confidential © Tech Mahindra 2006

Eg. : # Program to find the factorial of the given number

echo “ Enter The Given Number “read ni=1 f=1while [ $i –le $n ]do f=`expr $f \* $i` # f=`expr $f “*” $i` i=`expr $i + 1 `doneecho “Given Number = “ $n echo “ Factorial of the Given Number = “ $f

Statements (Contd.)

Page 39: Unix Shell Programming

04/08/23

3904/08/23Confidential © Tech Mahindra 2006

ii. until :This will execute the set of statements repeatedly

until the specified condition is false

Syntax :

Statements (Contd.)

a. until [ <condition> ]

do

statements

done

b. until test <condition>

do

statements

done

Page 40: Unix Shell Programming

04/08/23

4004/08/23Confidential © Tech Mahindra 2006

Eg. : # Program to find the factorial of the given number using until loop

echo “ Enter The Given Number “read ni=1 f=1until [ $i –gt $n ]do f=`expr $f \* $i` # f=`expr $f “*” $i` i=`expr $i + 1 `doneecho “Given Number = “ $n echo “ Factorial of the Given Number = “ $f

Statements (Contd.)

Page 41: Unix Shell Programming

04/08/23

4104/08/23Confidential © Tech Mahindra 2006

iii. forIt allows us to specify a list of values which the

control variable in the loop can take. The loop is then executed for each value mentioned in the list.Syntax :

for <variable> in <list of values/string> do st1;

done

Statements (Contd.)

Page 42: Unix Shell Programming

04/08/23

4204/08/23Confidential © Tech Mahindra 2006

Eg. : # Program to print all the sub-directories present in the current directory

echo “ Present Working Directory “ pwd echo “ The sub-directories under current

directory are : “ for i in * do if [ -d $i ] then echo -n $i fi done

Statements (Contd.)

Page 43: Unix Shell Programming

04/08/23

4304/08/23Confidential © Tech Mahindra 2006

break and continueIn shell programming we can use break and

continue keywords only in the looping statements (i.e., while , until & for ). a. break

It is used to come out of the loop.Syntax : a. break

b. break nThe first syntax is used to come out of the current

loop. But the later one is used to come out of the specified number of

loop.

Statements (Contd.)

Page 44: Unix Shell Programming

04/08/23

4404/08/23Confidential © Tech Mahindra 2006

Eg.:

Statements (Contd.)

echo “ Demo For Break St. “i=1 j=1while [ $i –le 10 ]do while [ $j –le 10] do if [ $j –eq 5 ] then break fi j=`expr $j + 1` done i=`expr $i + 1`done

Note :

In the above example for every value of i the inner loop i.e., j will get executed only till its value is equal to 5. Once when j value becomes 5 it comes out of the j loop because of a break statement, inside it.

Page 45: Unix Shell Programming

04/08/23

4504/08/23Confidential © Tech Mahindra 2006

Eg.:

Statements (Contd.)

echo “ Demo For Break St. “i=1 j=1while [ $i –le 10 ]do while [ $j –le 10] do if [ $j –eq 5 ] then break 2 fi j=`expr $j + 1` done i=`expr $i + 1`done

Note :

In the above example the outer loop will gets executed only once and the inner loop will get executed for 5 times, once the j value becomes 5 it comes out of both the loops because of the statement break 2 . It represents to the command interpreter to come out of the second loop.

Page 46: Unix Shell Programming

04/08/23

4604/08/23Confidential © Tech Mahindra 2006

b. continue It is used to move the control to the beginning of

the loop. (It is similar to Entry Point)Syntax : a. continue

b. continue n

The first syntax is used to move the control to the beginning of

the current loop where continue has been represented. But the later one

is used to move the control to the beginning of the nth loop from the

specified point.

Statements (Contd.)

Page 47: Unix Shell Programming

04/08/23

4704/08/23Confidential © Tech Mahindra 2006

Eg.:

Statements (Contd.)

echo “ Demo For Continue St. “i=1 j=1while [ $i –le 10 ]do while [ $j –le 10] do if [ $j –eq 5 ] then continue fi j=`expr $j + 1` done i=`expr $i + 1`done

Note :

In the above example for every value of i the inner loop i.e., j will get executed for infinite number of times because once when it becomes 5 it moves the control back to the beginning of j loop and the j value remains the same.

Page 48: Unix Shell Programming

04/08/23

4804/08/23Confidential © Tech Mahindra 2006

Eg.:

Statements (Contd.)

echo “ Demo For Continue St. “i=1 j=1while [ $i –le 10 ]do while [ $j –le 10] do if [ $j –eq 5 ] then continue 2 fi j=`expr $j + 1` done i=`expr $i + 1`done

Note :

In the above example for always i remains 1 because the inner loop i.e., j will get executed for infinite number of times because once when it becomes 5 it moves the control back to the beginning of i loop because of the statement continue 2and the i value remains the initial value.

Page 49: Unix Shell Programming

04/08/23

4904/08/23Confidential © Tech Mahindra 2006

Try Out ?

$echo *The above command will print all the files and

directories available on the present working directory.

$echo \* The above command will print the * on the

standard output device. Since it has been preceded by \.

$echo ‘***’ The above command will display *** since it

has been enclosed within quotes.

Page 50: Unix Shell Programming

04/08/23

5004/08/23Confidential © Tech Mahindra 2006

Try Out ?

$echo dateThe above command will print the word date on

the standard output device. The same can be given as echo ‘date’ (or) echo “date”

$echo `date` (Placed Within Ascent Graves ) The above command will execute the date

command and prints the result of the date command.

$echo `*` (or) echo `?` (Placed Within Ascent Graves )

The above command will generate error message stating that bash – permission denied because the * and ? are not commands to be placed within the ascent graves (or) reverse quotes.

Page 51: Unix Shell Programming

04/08/23

5104/08/23Confidential © Tech Mahindra 2006

Hands On…What will be the output of the above programs ?1.echo “ 1. ESG “echo “ 2. TIM”echo “ 3. HR”echo “ Enter Your Choice “read chcase $ch in 1) echo “ Welcome to Enr” 2) echo “ Welcome to ILI “ 3) echo “ Welcome to HRD” *) echo “ Invalid Input”esacO/p: Syntax Error near unexpected token (

2.echo “ 1. ESG “echo “ 2. TIM”echo “ 3. HR”echo “ Enter Your Choice “read chcase $ch in *) echo “ Invalid Input”;; 1) echo “ Welcome to Enr”;; 2) echo “ Welcome to ILI “;; 3) echo “ Welcome to HRD”;;esacO/p: For all the inputs it gives Invalid inputs.

Page 52: Unix Shell Programming

04/08/23

5204/08/23Confidential © Tech Mahindra 2006

Formatting the Output

tput command :The terminal capabilities are stored in a

file termcap inside /etc directory. Different ways of using tput

command is given below

tput clear : Clears the screentput cup r c : Moves the cursor to row r and

column c

Eg.: tput cup 10 5Moves the cursor to row 10 column 5

Note :Here cup denotes the cursor position.

Page 53: Unix Shell Programming

04/08/23

5304/08/23Confidential © Tech Mahindra 2006

Positional ParametersIt is otherwise called as Command Line arguments. It will be

represented by $1 to $9 (Whenever the variable name preceded by $ will be represented as positional parameters). We can assign the values for

the positional parameters from $1 to $9 either during the compile time or during the runtime (i.e., Using Command line arguments).

The shell reserves some variable names for its use, they are listed below.

Parameter Meaning

$$ Process Identification of the current shell

$? Exit status of the last executed command

$! Process Identification of last background process

$- Current Shell Settings

$# Total Number of Positional parameters

Page 54: Unix Shell Programming

04/08/23

5404/08/23Confidential © Tech Mahindra 2006

Positional Parameters (Contd.)

Parameter Meaning

$0 Name of the command being used

$* List of all shell arguments. Can’t yield each argument separately.

$@ Similar to $* , but yields each argument separately when enclosed in double quotes.

Page 55: Unix Shell Programming

04/08/23

5504/08/23Confidential © Tech Mahindra 2006

Setting Values of Positional Parametersa. During the Runtime

# Program to check whether given two strings are equal or

not using command line arguments. if [ $1 = $2 ]

then echo Strings are Equal $1 $2

else echo Strings are not Equal $1 $2 fi echo Total Number of Positional

Parameters $# echo List of Shell Arguments $*

Positional Parameters (Contd.)

Page 56: Unix Shell Programming

04/08/23

5604/08/23Confidential © Tech Mahindra 2006

I/P For the above ProgramSyntax : sh <name of the prog.> <value1

value2 . . .>Eg.: $ sh pos1.sh bms bms

Note : In the above input $0 will have the name of

the file i.e, pos1.sh as its value, $1 will have the value as bms & $2 has

the value as bms.

O/P : Strings are Equal Total Number of Positional parameters 2

List of Shell Arguments bms bms

Positional Parameters (Contd.)

Page 57: Unix Shell Programming

04/08/23

5704/08/23Confidential © Tech Mahindra 2006

b. During the Compile time# Program to assign the value for the

positional parameterduring the compile time.set Doubt Your Doubts Never Your Beliefsecho Value of \$1 $1echo Value of \$2 $2echo Value of \$3 $3echo Value of \$4 $4echo Value of \$5 $5echo Value of \$6 $6

Positional Parameters (Contd.)

Note : The slash has been preceded

before the $ sign in echo statement toprint that $1 and so on as it is , otherwise it will print the value of that positional Parameter.

$1 will have the value Doubt and $2 will have the value Your and so on.

Page 58: Unix Shell Programming

04/08/23

5804/08/23Confidential © Tech Mahindra 2006

b. During the Compile time# Program to assign the value for the

positional parameterduring the compile time.set Happiness what U Give Makes U More

Happy Than TheHappiness What U Receive.echo Value of \$9 $9echo Value of \$10 $10echo Value of \$12 $12echo Value of \$20 $20

Positional Parameters (Contd.)

Note : While we are assigning a value for

the positional parameter, it can assign values only to 9 positional parameters by default. In the above program while we are accessing the positional parameter $10 willhave the first value followed by 0 i.e, Happiness0 , $12 = Happiness2$20 = what0

Page 59: Unix Shell Programming

04/08/23

5904/08/23Confidential © Tech Mahindra 2006

How to Resolve the Ambiguity ?To print the entire value of the string given in the set

command using positional parameter we have to use shift command. Using shift command we can move the control to the specified number of

tokens and regenerate the positional parameters from that point.

Syntax : shift <number>Eg.: shift 3

Note :The number represented in shift command should be a

positive number (i.e., >= 0 and <= the total no. of words given in the set command) . If we are not giving any values by default it takes as 1.

If we are giving the value > total no. of words given in the set command, the command interpreter starts from the beginning.

Positional Parameters (Contd.)

Page 60: Unix Shell Programming

04/08/23

6004/08/23Confidential © Tech Mahindra 2006

b. During the Compile time# Program to assign the value for the positional

parameterduring the compile time using shift.set Happiness what U Give Makes U More Happy

Than TheHappiness What U Receive.echo Before Shiftingecho Value of \$1 $1echo Value of \$2 $2echo Value of \$3 $3echo Value of \$9 $9

shift 9 echo After Shifting

echo Value of \$1 $1echo Value of \$2 $2echo Value of \$3 $3

Positional Parameters (Contd.)

Note : The shift command is used to

move 9 tokens towards the right and reinitialize the positional parameters. After shifting $1 = The $2 = Happiness $3 = What

Page 61: Unix Shell Programming

04/08/23

6104/08/23Confidential © Tech Mahindra 2006

# Demo For $* and $@ parameters cat “$*” cat “$@”I/P :

sh pos10.sh pos1.sh pos2.sh pos3.sh

O/P:While executing the first cat command will

produce an error stating that there is no file named “pos1.sh pos2.sh pos3.sh”. But the later one will display the content of the files pos1.sh , pos2.sh & pos3.sh respectively.

Note : If the above commands has been issued without quotes both will give the same results

Positional Parameters (Contd.)

# interpreted as cat “pos1.sh pos2.sh pos3.sh”# interpreted as cat “pos1.sh” “pos2.sh” “pos3.sh”

Page 62: Unix Shell Programming

04/08/23

6204/08/23Confidential © Tech Mahindra 2006

Exporting Variables

A variable can be made available to its sub shell through export

commandSyntax

export <Variable1 . . .>

A variable can be exported either before or after it is defined. Eg.:

i. export a

a=100

ii. a=100

export a

Page 63: Unix Shell Programming

04/08/23

6304/08/23Confidential © Tech Mahindra 2006

Note : 1. We can export the variables only from the parent to the child program. But the reverse is not true. 2. The Changes Made in the child program will never get reflected to the parent program. 3. The Program which we are calling inside the parent program should have an execute permission. Otherwise it give an error

message stating that permission denied. 4. We can export the Variables from one shell to another shell.

Exporting Variables (Contd)

Page 64: Unix Shell Programming

04/08/23

6404/08/23Confidential © Tech Mahindra 2006

Exporting Variables (Contd)

# Program For Exporting the # Variable from one program to # Another program a=10export aecho “ Value of A in expo.sh “ $a#Calling expo1.sh programexpo1.shecho “ After Calling expo1.sh “ $a

#Sub program using the export# Variable echo “ Value of A = “ $aa=`expr $a + 10`echo “ Value of A = “ $a

Note : The Values Changed in the

Child Prog. will never get reflected to the Main Prog.

Page 65: Unix Shell Programming

04/08/23

6504/08/23Confidential © Tech Mahindra 2006

Signals & Trap Command Signals in general tend to terminate a process. trap command allows to handle the signal Important signals

Signal Key Combination Code Value

Hang up Ctrl d 1

Interrupt Ctrl c 2

Terminate kill 15

Page 66: Unix Shell Programming

04/08/23

6604/08/23Confidential © Tech Mahindra 2006

Signals (Contd.)

Syntax : trap “<commands>” <signal-list>

Eg. :trap “ls –al” 2

Lists the current directory contents when ctrl-c is hit

Note : 1. trap command, once it has been read in, lies in

wait for those signals mentioned in the signal list. When

such a signal shows up, the command is performed

instead of the default behavior

2. trap command will trap the signals only during the execution of the shell scripts

Page 67: Unix Shell Programming

04/08/23

6704/08/23Confidential © Tech Mahindra 2006

Summary

Uses of Shell Scripts Variables Type Conversions Statements Positional Parameters Export Signals Trap Commands