Operator Meaning
string1 = string2 string1 is equal to string2
string1 != string2 string1 is NOT equal to string2
string1 string1 is NOT NULL or not defined
-n string1 string1 is NOT NULL and does exist
-z string1 string1 is NULL and does exist
Shell also test for file and directory types
Test Meaning
-s file Non empty file
-f file Is File exist or normal file and not a directory
-d dir Is Directory exist and not a file
-w file Is writeable file
-r file Is read-only file
-x file Is file is executable
Logical Operators
Logical operators are used to combine two or more condition at a time
Operator Meaning
! expression Logical NOT
expression1 -a expression2 Logical AND
expression1 -o expression2 Logical OR
if...else...fi
If given condition is true then command1 is executed otherwise
command2 isexecuted.
Syntax:
if
conditi
onthen
condition is zero (true - 0)
execute all commands up to else statement
else
if condition is not true
then execute all
commands up to fi
fi
For e.g. Write Script as follows:
$ vi
isnump_n
#!/bin/sh
#
Script to see whether argument is positive or negative

if [ $# -eq 0
] then
echo "$0 : You must give/supply
oneintegers" exit 1
fi
if test $1
-gt 0then
echo "$1 number is
positive"else
echo "$1 number is
negative"fi
Try it as follows:
$ chmod 755 isnump_n
$ isnump_n 5
5 number is positive
$ isnump_n -45
-45 number is negative
$ isnump_n
./ispos_n : You must give/supply one integers
$ isnump_n 0
1 number is negative
Detailed explanation
First script checks whether command line argument is given or not, if not
given then it print error message as "./ispos_n : You must give/supply one
integers". if statement checks whether number of argument ($#) passed to
script is not equal (-eq) to 0, if we passed any argument to script then this if
statement is false and if no command line argument is given then this if
statement is true. The echo command i.e.
echo "$0 : You must give/supply one integers"
| |
| |
1 2
2 will print Name of script
3 will print this error message
And finally statement exit 1 causes normal program termination with exit status
1(nonzero means script is not successfully run).
$ vi nestedif.sh
osch=0
echo "1. Unix (Sun Os)"
The last sample run $ isnump_n 0 , gives output as "0 number is negative",
because given argument is not > 0, hence condition is false and it's taken as
negative number. To avoid this replace second if statement with if test $1 -ge
0.
Nested if-else-fi
You can write the entire if-else construct within either the body of the if
statementof the body of an else statement. This is called the nesting of ifs.
echo "2. Linux (Red Hat)"
echo -n "Select your os choice [1 or
2]? "read osch
echo "You Pick up Linux (Red Hat)"
else
echo "What you don't like Unix/Linux OS."
fi
fi
Run the above shell script as follows:
$ chmod +x nestedif.sh
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or
2]? 1
You Pick up Unix (Sun Os)
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or
2]? 2You Pick up Linux
(Red Hat)
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or
2]? 3
if [ $osch -eq 1 ] ; then
echo "You Pick up Unix (Sun Os)"
else #### nested if i.e. if within if ######
if [ $osch -eq 2 ] ; then
What you don't like Unix/Linux OS.
Note that Second if-else constuct is nested in the first else statement. If
thecondition in the first if statement is false the the condition in the
second if statement is checked. If it is false as well the final
elsestatement isexecuted.
You can use the nested ifs as follows also:
Syntax:
if
conditi
onthen
if
conditi
onthen
.....
else
..
do this
....
else
fi
...
.....
do this
do this
f
Multilevel if-then-else
Syntax:
if
conditi
onthen
condition is zero (true - 0)
execute all commands up to elif
statementelif condition1
then
condition1 is zero (true - 0)
execute all commands up to elif
statementelif condition2
then
else
condition2 is zero (true - 0)
execute all commands up to elif statement
None of the above condtion,condtion1,condtion2 are true (i.e.
all of the above nonzero or false)
execute all commands up to fi
Loops in Shell Scripts
Loop defined as:
"Computer can repeat particular instruction again and again, until
particular condition satisfies. A group of instruction that is executed
repeatedly is called aloop."
Bash supports:
 for loop
 while loop
for Loop
Syntax:
for { variable name } in { list }
do
execute one for each item in the list until the list is
not finished (And repeat all statement between do and done)
done
$ cat > mtable
#!/bin/sh
#
#Script to test for loop
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
$ cat > testfor
for i in 1 2 3 4 5
Before try to understand above syntax try the following script:
do
echo "Welcome $i
times"done
Run it above script as follows:
$ chmod +x testfor
$ ./testfor
The for loop first creates i variable and assigned a number to i from the list of
number from 1 to 5, The shell execute echo statement for each assignment of i.
(This is usually know as iteration) This process will continue until all the items
in the list were not finished, because of this it will repeat 5 echo statements. To
makeyou idea more clear try following script:
echo "Syntax : $0 number"
echo "Use to print multiplication table for given
number"exit 1
f
i
n
=
$
1
for i in 1 2 3 4 5 6 7 8
9 10do
echo "$n * $i = `expr $i *
$n`"done
Save above script and run it as:
$ chmod 755 mtable
$ ./mtable 7
$ ./mtable
For first run, above script print multiplication table of given number where i = 1,2
... 10 is multiply by given n (here command line argument 7) in order to
producemultiplication table as
7 * 1 = 7
7 * 2 = 14
...
..
7 * 10 = 70
And for second test run, it will print message -
Error - Number missing form command line
argumentSyntax : ./mtable number
Use to print multiplication table for given number
This happened because we have not supplied given number for which we
want multiplication table, Hence script is showing Error message, Syntax
and usage of our script. This is good idea if our program takes some
argument, let the userknow what use of the script is and how to use the
script.
Note that to terminate our script we used 'exit 1' command which
takes 1as argument (1 indicates error and therefore script is
terminated)
Even you can use following syntax:
Syntax:
for (( expr1; expr2;
expr3 ))do
.....
...
repeat all statements between do
anddone until expr2 is TRUE
Done
In above syntax BEFORE the first iteration, expr1 is evaluated.
This isusually used to initialize variables for the loop.
All the statements between do and done is executed repeatedly UNTIL the
valueof expr2 is TRUE.
AFTER each iteration of the loop, expr3 is evaluated. This is usually
use toincrement a loop counter.
$ cat > for2
for (( i = 0 ; i <= 5;
i++ ))do
echo "Welcome $i
times"done
Run the above script as follows:
$ chmod +x for2
$ ./for2
Welcome 0 times
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
In above example, first expression (i = 0), is used to set the value variable
i tozero.
Second expression is condition i.e. all statements between do and done
executedas long as expression 2 (i.e continue as long as the value of variable
i is less thanor equel to 5) is TRUE.
Last expression i++ increments the value of i by 1 i.e. it's equivalent to i = i
+ 1statement.
$ vi nestedfor.sh
for (( i = 1; i <= 5; i++ ))### Outer for loop ###
do
for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ###
do
Nesting of for Loop
As you see the if statement can nested, similarly loop statement can be nested.
You can nest the for loop. To understand the nesting of for loop see the
followingshell script.
echo -n
"$i "done
echo "" #### print the new line ###
done
Run the above script as follows:
$ chmod +x nestedfor.sh
$ ./nestefor.sh
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Here, for each value of i the inner loop is cycled through 5 times, with the
varible j taking values from 1 to 5. The inner for loop terminates when the
value of j exceeds 5, and the outer loop terminets when the value of i
exceeds 5.
while loop
Syntax:
while [
condition ]do
command3
command1
command2
..
....
done
$cat > nt1
#!/bin/sh
#
#Script to test while statement
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
Loop is executed as long as given condition is true. For e.g.. Above for
loop program (shown in last section of for loop) can be written using while
loop as:
echo " Use to print multiplication table for given
number"exit 1
f
i
n
=
$
1
i
=
1
while [ $i -le 10 ]
do
echo "$n * $i = `expr $i *
$n`"i=`expr $i + 1`
done
The case Statement
The case statement is good alternative to multilevel if-then-else-fi
statement. Itenable you to match several values against one variable. It’s
easier to read and write.
Syntax:
case $variable-name in
pattern1)command
...
..
command;;
pattern2) command
...
..
command;;
patternN) command
...
..
command;;
*) command
...
..
command;;
esac
The $variable-name is compared against the patterns until a match is found.
Theshell then executes all the statements up to the two semicolons that are
next to each other. The default is *) and its executed if no match is found.
For e.g. writescript as follows:
$ cat > car
#
if no vehicle name is given
i.e. -z $1 is defined and it is NULL

if no command line arg
if [ -z $1 ]
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
otherwise make first arg as rental rental=$1
fi
case $rental in
"car") echo "For $rental
Rs.20 per k/m";;"van")
echo "For $rental Rs.10
per k/m";;
"jeep") echo "For $rental Rs.5
per k/m";; "bicycle") echo
"For $rental 20 paisa per
k/m";;
*) echo "Sorry, I can not gat a
$rental for you";;esac

More Related Content

PDF
PPTX
Unix Shell Programming subject shell scripting ppt
PPTX
AOS_Module_3ssssssssssssssssssssssssssss.pptx
PPS
UNIX - Class3 - Programming Constructs
PPTX
Scripting ppt
PPTX
Case, Loop & Command line args un Unix
PDF
Operating_System_Lab_ClassOperating_System_2.pdf
PPT
Bash Programming
Unix Shell Programming subject shell scripting ppt
AOS_Module_3ssssssssssssssssssssssssssss.pptx
UNIX - Class3 - Programming Constructs
Scripting ppt
Case, Loop & Command line args un Unix
Operating_System_Lab_ClassOperating_System_2.pdf
Bash Programming

Similar to Osp2.pdf (20)

DOCX
What is a shell script
PPT
Advanced linux chapter ix-shell script
PPTX
Licão 12 decision loops - statement iteration
PPTX
Scripting 101
PPTX
Shell Programming Language in Operating System .pptx
PPTX
Scripting ppt
PDF
Control flow and related shell cripts
PPT
Shell programming
PPT
ShellAdvanced shell scripting programm.ppt
PPT
ShellProgramming and Script in operating system
PPTX
Unix shell scripts
PPT
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
PPTX
Bash and regular expressions
PPT
Unix Shell Scripting Basics
PPT
Unix shell scripting basics
PPTX
Linux Shell Scripting
PPTX
shellScriptAlt.pptx
PPT
PDF
Shell Scripting Structured Commands
PDF
003 scripting
What is a shell script
Advanced linux chapter ix-shell script
Licão 12 decision loops - statement iteration
Scripting 101
Shell Programming Language in Operating System .pptx
Scripting ppt
Control flow and related shell cripts
Shell programming
ShellAdvanced shell scripting programm.ppt
ShellProgramming and Script in operating system
Unix shell scripts
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
Bash and regular expressions
Unix Shell Scripting Basics
Unix shell scripting basics
Linux Shell Scripting
shellScriptAlt.pptx
Shell Scripting Structured Commands
003 scripting
Ad

Recently uploaded (20)

PPTX
Computer Architecture Input Output Memory.pptx
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
HVAC Specification 2024 according to central public works department
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
semiconductor packaging in vlsi design fab
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
PDF
Hazard Identification & Risk Assessment .pdf
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
PPTX
Education and Perspectives of Education.pptx
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
International_Financial_Reporting_Standa.pdf
Computer Architecture Input Output Memory.pptx
B.Sc. DS Unit 2 Software Engineering.pptx
A powerpoint presentation on the Revised K-10 Science Shaping Paper
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
HVAC Specification 2024 according to central public works department
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
semiconductor packaging in vlsi design fab
Share_Module_2_Power_conflict_and_negotiation.pptx
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
Hazard Identification & Risk Assessment .pdf
Race Reva University – Shaping Future Leaders in Artificial Intelligence
Education and Perspectives of Education.pptx
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Environmental Education MCQ BD2EE - Share Source.pdf
International_Financial_Reporting_Standa.pdf
Ad

Osp2.pdf

  • 1. Operator Meaning string1 = string2 string1 is equal to string2 string1 != string2 string1 is NOT equal to string2 string1 string1 is NOT NULL or not defined -n string1 string1 is NOT NULL and does exist -z string1 string1 is NULL and does exist Shell also test for file and directory types Test Meaning -s file Non empty file -f file Is File exist or normal file and not a directory -d dir Is Directory exist and not a file -w file Is writeable file -r file Is read-only file -x file Is file is executable
  • 2. Logical Operators Logical operators are used to combine two or more condition at a time Operator Meaning ! expression Logical NOT expression1 -a expression2 Logical AND expression1 -o expression2 Logical OR if...else...fi If given condition is true then command1 is executed otherwise command2 isexecuted. Syntax: if conditi onthen condition is zero (true - 0) execute all commands up to else statement else if condition is not true then execute all commands up to fi fi For e.g. Write Script as follows:
  • 3. $ vi isnump_n #!/bin/sh # Script to see whether argument is positive or negative  if [ $# -eq 0 ] then echo "$0 : You must give/supply oneintegers" exit 1 fi if test $1 -gt 0then echo "$1 number is positive"else echo "$1 number is negative"fi Try it as follows: $ chmod 755 isnump_n
  • 4. $ isnump_n 5 5 number is positive $ isnump_n -45 -45 number is negative $ isnump_n ./ispos_n : You must give/supply one integers $ isnump_n 0 1 number is negative Detailed explanation First script checks whether command line argument is given or not, if not given then it print error message as "./ispos_n : You must give/supply one integers". if statement checks whether number of argument ($#) passed to script is not equal (-eq) to 0, if we passed any argument to script then this if statement is false and if no command line argument is given then this if statement is true. The echo command i.e. echo "$0 : You must give/supply one integers" | | | | 1 2 2 will print Name of script 3 will print this error message And finally statement exit 1 causes normal program termination with exit status 1(nonzero means script is not successfully run).
  • 5. $ vi nestedif.sh osch=0 echo "1. Unix (Sun Os)" The last sample run $ isnump_n 0 , gives output as "0 number is negative", because given argument is not > 0, hence condition is false and it's taken as negative number. To avoid this replace second if statement with if test $1 -ge 0. Nested if-else-fi You can write the entire if-else construct within either the body of the if statementof the body of an else statement. This is called the nesting of ifs. echo "2. Linux (Red Hat)" echo -n "Select your os choice [1 or 2]? "read osch
  • 6. echo "You Pick up Linux (Red Hat)" else echo "What you don't like Unix/Linux OS." fi fi Run the above shell script as follows: $ chmod +x nestedif.sh $ ./nestedif.sh 1. Unix (Sun Os) 2. Linux (Red Hat) Select you os choice [1 or 2]? 1 You Pick up Unix (Sun Os) $ ./nestedif.sh 1. Unix (Sun Os) 2. Linux (Red Hat) Select you os choice [1 or 2]? 2You Pick up Linux (Red Hat) $ ./nestedif.sh 1. Unix (Sun Os) 2. Linux (Red Hat) Select you os choice [1 or 2]? 3 if [ $osch -eq 1 ] ; then echo "You Pick up Unix (Sun Os)" else #### nested if i.e. if within if ###### if [ $osch -eq 2 ] ; then
  • 7. What you don't like Unix/Linux OS. Note that Second if-else constuct is nested in the first else statement. If thecondition in the first if statement is false the the condition in the second if statement is checked. If it is false as well the final elsestatement isexecuted. You can use the nested ifs as follows also: Syntax: if conditi onthen if conditi onthen ..... else .. do this .... else fi ... ..... do this do this f Multilevel if-then-else Syntax: if conditi onthen condition is zero (true - 0) execute all commands up to elif statementelif condition1 then
  • 8. condition1 is zero (true - 0) execute all commands up to elif statementelif condition2 then else condition2 is zero (true - 0) execute all commands up to elif statement None of the above condtion,condtion1,condtion2 are true (i.e. all of the above nonzero or false) execute all commands up to fi Loops in Shell Scripts Loop defined as: "Computer can repeat particular instruction again and again, until particular condition satisfies. A group of instruction that is executed repeatedly is called aloop." Bash supports:  for loop  while loop for Loop Syntax: for { variable name } in { list } do execute one for each item in the list until the list is not finished (And repeat all statement between do and done) done
  • 9. $ cat > mtable #!/bin/sh # #Script to test for loop # # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" $ cat > testfor for i in 1 2 3 4 5 Before try to understand above syntax try the following script: do echo "Welcome $i times"done Run it above script as follows: $ chmod +x testfor $ ./testfor The for loop first creates i variable and assigned a number to i from the list of number from 1 to 5, The shell execute echo statement for each assignment of i. (This is usually know as iteration) This process will continue until all the items in the list were not finished, because of this it will repeat 5 echo statements. To makeyou idea more clear try following script: echo "Syntax : $0 number" echo "Use to print multiplication table for given number"exit 1 f i n = $ 1
  • 10. for i in 1 2 3 4 5 6 7 8 9 10do echo "$n * $i = `expr $i * $n`"done Save above script and run it as: $ chmod 755 mtable $ ./mtable 7 $ ./mtable For first run, above script print multiplication table of given number where i = 1,2 ... 10 is multiply by given n (here command line argument 7) in order to producemultiplication table as 7 * 1 = 7 7 * 2 = 14 ... .. 7 * 10 = 70 And for second test run, it will print message -
  • 11. Error - Number missing form command line argumentSyntax : ./mtable number Use to print multiplication table for given number This happened because we have not supplied given number for which we want multiplication table, Hence script is showing Error message, Syntax and usage of our script. This is good idea if our program takes some argument, let the userknow what use of the script is and how to use the script. Note that to terminate our script we used 'exit 1' command which takes 1as argument (1 indicates error and therefore script is terminated) Even you can use following syntax: Syntax: for (( expr1; expr2; expr3 ))do ..... ... repeat all statements between do anddone until expr2 is TRUE Done In above syntax BEFORE the first iteration, expr1 is evaluated. This isusually used to initialize variables for the loop. All the statements between do and done is executed repeatedly UNTIL the valueof expr2 is TRUE. AFTER each iteration of the loop, expr3 is evaluated. This is usually use toincrement a loop counter.
  • 12. $ cat > for2 for (( i = 0 ; i <= 5; i++ ))do echo "Welcome $i times"done Run the above script as follows: $ chmod +x for2 $ ./for2 Welcome 0 times Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times In above example, first expression (i = 0), is used to set the value variable i tozero. Second expression is condition i.e. all statements between do and done executedas long as expression 2 (i.e continue as long as the value of variable i is less thanor equel to 5) is TRUE. Last expression i++ increments the value of i by 1 i.e. it's equivalent to i = i + 1statement.
  • 13. $ vi nestedfor.sh for (( i = 1; i <= 5; i++ ))### Outer for loop ### do for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ### do Nesting of for Loop As you see the if statement can nested, similarly loop statement can be nested. You can nest the for loop. To understand the nesting of for loop see the followingshell script. echo -n "$i "done echo "" #### print the new line ### done Run the above script as follows: $ chmod +x nestedfor.sh $ ./nestefor.sh 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
  • 14. Here, for each value of i the inner loop is cycled through 5 times, with the varible j taking values from 1 to 5. The inner for loop terminates when the value of j exceeds 5, and the outer loop terminets when the value of i exceeds 5. while loop Syntax: while [ condition ]do command3 command1 command2 .. .... done
  • 15. $cat > nt1 #!/bin/sh # #Script to test while statement # # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" echo "Syntax : $0 number" Loop is executed as long as given condition is true. For e.g.. Above for loop program (shown in last section of for loop) can be written using while loop as: echo " Use to print multiplication table for given number"exit 1 f i n = $ 1 i = 1 while [ $i -le 10 ] do echo "$n * $i = `expr $i * $n`"i=`expr $i + 1` done The case Statement The case statement is good alternative to multilevel if-then-else-fi statement. Itenable you to match several values against one variable. It’s easier to read and write.
  • 16. Syntax: case $variable-name in pattern1)command ... .. command;; pattern2) command ... .. command;; patternN) command ... .. command;; *) command ... .. command;; esac The $variable-name is compared against the patterns until a match is found. Theshell then executes all the statements up to the two semicolons that are next to each other. The default is *) and its executed if no match is found. For e.g. writescript as follows:
  • 17. $ cat > car # if no vehicle name is given i.e. -z $1 is defined and it is NULL  if no command line arg if [ -z $1 ] then rental="*** Unknown vehicle ***" elif [ -n $1 ] then otherwise make first arg as rental rental=$1 fi case $rental in "car") echo "For $rental Rs.20 per k/m";;"van") echo "For $rental Rs.10 per k/m";; "jeep") echo "For $rental Rs.5 per k/m";; "bicycle") echo "For $rental 20 paisa per k/m";; *) echo "Sorry, I can not gat a $rental for you";;esac