SlideShare a Scribd company logo
Lesson 12
• Decision with Loops
• Statement Iteration
• While
• Until
• For
• Select
• Nesting loops
• Loop Control
• Infinite
• Break
• Continue
Decision Making with loops
Iteration Statements
Loops
Powerful programming tool that enables execution of a set of commands
repeatedly.
• The while loop
• The for loop
• The until loop
• The select loop
Nesting Loops
All loops support nesting
– You can put one loop inside another similar or different loops.
This nesting can go up to unlimited number of times based on your requirement.
while loop
while loop iterates “while” the expression is true
enables to execute a set of commands repeatedly until some condition occurs.
It is usually used to manipulate the value of a variable repeatedly.
• It’s a looping structure. Executes a set of commands while a specified condition is true.
• The loop terminates as soon as the condition becomes false.
• If condition never becomes false, loop will never exit.
Syntax:
while command
do
Statement(s) to be executed if command is true
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.
while loop
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
example display the numbers zero to nine
0
1
2
3
4
5
6
7
8
9
example result
• Each time this loop executes, the variable a is checked to see
whether it has a value that is less than 10.
• If the value of a is less than 10, this test condition has an exit
status of 0.
• In this case, current value of a is displayed, then a is incremented
by 1.
while loop
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
let COUNTER+=1
done
example
#!/bin/bash
while read line; do
echo $line
done < /etc/passwd
example
while loop
$ vi while.sh
#!/bin/bash
echo –n “Enter a number: ”; read x
sum=0
i=1
while [ $i –le $x ]; do
sum=$[sum+i]
i=$[i+1]
done
echo “the sum of the first $x numbers is: $sum”
example
while loop
$ vi menu.sh
#!/bin/bash
clear ; loop=y
while [ “$loop” = y ] ;
do
echo “Menu”; echo “====”
echo “D: print the date”
echo “W: print the users who are currently log on.”
echo “P: print the working directory”
echo “Q: quit.”
echo
read –s choice # silent mode: no echo to terminal
case $choice in
D | d) date ;;
W | w) who ;;
P | p) pwd ;;
Q | q) loop=n ;;
*) echo “Illegal choice.” ;;
esac
echo
done
example
until loop
until loop will execute the loop while the expression evaluates to false
while loop is perfect to execute a set of commands while some condition is true.
until loop is when u need to execute a set of cmds until a condition is true.
• Similar to the while structure.
• until structure loops until the condition is true. “until this condition is true, do this”.
Syntax:
until command
do
Statement(s) to be executed until command is true
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.
until loop
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
example
0
1
2
3
4
5
6
7
8
9
example result
until loop
#!/bin/bash
COUNTER=10
until [ $COUNTER -lt 1 ]; do
let COUNTER-=1
done
example
until loop
$ vi countdown.sh
#!/bin/bash
echo “Enter a number: ”; read x
echo ; echo Count Down
until [ “$x” -le 0 ]; do
echo $x
x=$(($x –1))
sleep 1
done
echo ; echo GO !
example
for loop
for loop
Operates on lists of items. used when you are looping through a range of
variables. It repeats a set of commands for every item in a list.
statements are executed with var set to each value in the list
Syntax:
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
• var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words).
• Each time the for loop executes, value of the variable var is set to the next word in
the list of words, word1 to wordN.
for loop
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
example span list numbers
0
1
2
3
4
5
6
7
8
9
example result
for loop
#!/bin/sh
for FILE in $HOME/.bash*
do
echo $FILE
done
example display all the files starting with .bash and available in your home. executing from my root
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
example result
for loop
#!/bin/bash
let sum=0
for num in 1 2 3 4 5
do
let “sum = $sum + $num”
done
echo $sum
example
for loop
#!/bin/bash
for i in $(ls); do
echo $i
done
example
#!/bin/bash
for i in $(seq 10); do
echo $i
done
example
for loop
#!/bin/bash
for x in paper pencil pen
do
echo “The value of variable x is: $x”
sleep 1
done
$vi for1.sh
#!/bin/bash
for x
do
echo “The value of variable x is: $x”
sleep 1
done
$ for1.sh arg1 arg2
The value of variable x is: arg1
The value of variable x is: arg2
if the list part is left off, var is set to each parameter passed to the script ( $1, $2, $3,…)
example
for loop
$ vi old.sh
#!/bin/bash
# Move the command line arg files to old directory.
if [ $# -eq 0 ] #check for command line arguments
then
echo “Usage: $0 file …”
exit 1
fi
if [ ! –d “$HOME/old” ]
then
mkdir “$HOME/old”
fi
echo The following files will be saved in the old directory:
echo $*
for file in $* #loop through all command line arguments
do
mv $file “$HOME/old/”
chmod 400 “$HOME/old/$file”
done
ls -l “$HOME/old”
example
for loop
$ vi args.sh
#!/bin/bash
# Invoke this script with several arguments: “one two three“
if [ ! -n “$1” ]; then
echo “Usage: $0 arg1 arg2 ..." ; exit 1
fi
echo ; index=1 ;
echo “Listing args with ”$*”:”
for arg in “$*” ;
do
echo “Arg $index = $arg”
let “index+=1” # increase variable index by one
done
echo “Entire arg list seen as single word.”
echo ; index=1 ;
echo “Listing args with ”$@”:”
for arg in “$@” ; do
echo “Arg $index = $arg”
let “index+=1”
done
echo “Arg list seen as separate words.” ; exit 0
example
C-like for loop
An alternative form of for structure is
for (( EXPR1 ; EXPR2 ; EXPR3 ))
do
statements
done
• First, the arithmetic expression EXPR1 is evaluated.
• EXPR2 is then evaluated repeatedly until it evaluates to 0.
• Each time EXPR2 is evaluates to a non-zero value, statements are executed and EXPR3
is evaluated.
$ vi for2.sh
#!/bin/bash
echo –n “Enter a number: ”; read x
let sum=0
for (( i=1 ; $i<$x ; i=$i+1 )) ; do
let “sum = $sum + $i”
done
echo “the sum of the first $x numbers is: $sum”
select loop
select loop (fuction is like a for loop with menu selection)
Easy way to create a numbered menu from which users can select options.
Useful for asking the user to choose one or more items from a list of choices.
Syntax:
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
• var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words).
• Each time the for loop executes, the value of the variable var is set to the next word
in the list of words, word1 to wordN.
• For every selection a set of commands would be executed with-in the loop.
loop was introduced in ksh and has been adapted into bash. It is not available in sh.
select loop
#!/bin/bash
select DRINK in tea cofee water juice appe all none
do
case $DRINK in
tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
example let the user select a drink of choice (A)
select loop
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
example result
select loop
$PS3="Please make a selection => " ; export PS3
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$
example alternate let the user select a drink of choice (B)
change the prompt displayed by the select loop by altering the variable PS3
Nesting while Loops
while loop as part of the body of another while loop
Syntax:
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true
while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done
Statement(s) to be executed if command1 is true
done
Nesting while Loops
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
example add another countdown loop inside the loop used to count to nine
Nesting while Loops
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0
example result
echo -n option let echo to avoid printing a new line character
Loop Control
Loop control is needed to stop a loop or skip iterations of the loop
two statements used to control shell loops
break statement
continue statement
The infinite Loop
• loops have a limited life and they execute once the condition is false or true
• loop may continue forever due to required condition is not met.
A loop that executes forever without terminating executes an infinite number of times.
Is called infinite loops.
#!/bin/sh
a=10
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Break statement
Break statement
Used to terminate the execution of the entire loop, after completing the execution
of all of the lines of code up to the break statement. It then goes to the code
following the end of the loop.
Syntax:
break
break command can also be used to exit from a nested loop using this format:
break n #n specifies the nth enclosing loop to exit from
.
Break statement
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
example loop would terminate as soon as a becomes 5
0
1
2
3
4
5
example result
Break statement
$ vi break.sh
#!/bin/bash
LIMIT=19
echo
echo “Printing Numbers 1 through 20, but something happens after 2 … ”
a=0
while [ $a -le “$LIMIT” ]
do
a=$(($a+1))
if [ “$a” -gt 2 ]
then
break
fi
echo -n “$a ”
done
echo; echo; echo
exit 0
example
continue statement
continue statement
Similar to break command
except that causes the current iteration of the loop to exit, rather than entire loop.
That is It causes a jump to the next iteration of the loop, skipping all the remaining
commands in that particular loop cycle
This statement is useful when an error has occurred but you want to try to execute the next
iteration of the loop.
Syntax:
continue
an integer argument can be given to the continue command to skip commands from nested loops:
continue n #n specifies the nth enclosing loop to continue from
.
continue statement
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
example
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
example result
continue statement
$ vi continue.sh
#!/bin/bash
LIMIT=19
echo
echo “Printing Numbers 1 through 20 (but not 3 and 11)”
a=0
while [ $a -le “$LIMIT” ]; do
a=$(($a+1))
if [ “$a” -eq 3 ] || [ “$a” -eq 11 ]
then
continue
fi
echo -n “$a ”
done
example

More Related Content

PDF
Shell Script
PPTX
Unix shell scripts
PPTX
Bash Shell Scripting
PDF
PPTX
Linux System Administration
PPTX
Linux Shell Scripting
PPT
Unix Shell Scripting Basics
PPTX
Unix shell scripting
Shell Script
Unix shell scripts
Bash Shell Scripting
Linux System Administration
Linux Shell Scripting
Unix Shell Scripting Basics
Unix shell scripting

What's hot (20)

PDF
Shell script-sec
PPTX
Shell Script Tutorial
PDF
Linux fundamental - Chap 14 shell script
PPT
Chap06
PPT
Bash shell
PPTX
Mastering unix
PPT
2-introduction_to_shell_scripting
PDF
Beautiful Bash: Let's make reading and writing bash scripts fun again!
PDF
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
PDF
Shell scripting
PPT
Shell Scripting
PDF
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
PPT
Unix Shell Scripting Basics
PDF
BASH Guide Summary
PPTX
Easiest way to start with Shell scripting
PPTX
Unix - Shell Scripts
PDF
Introduction to shell scripting
PDF
Memory Manglement in Raku
PPTX
Shell programming 1.ppt
PPT
Talk Unix Shell Script
Shell script-sec
Shell Script Tutorial
Linux fundamental - Chap 14 shell script
Chap06
Bash shell
Mastering unix
2-introduction_to_shell_scripting
Beautiful Bash: Let's make reading and writing bash scripts fun again!
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
Shell scripting
Shell Scripting
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Unix Shell Scripting Basics
BASH Guide Summary
Easiest way to start with Shell scripting
Unix - Shell Scripts
Introduction to shell scripting
Memory Manglement in Raku
Shell programming 1.ppt
Talk Unix Shell Script
Ad

Viewers also liked (9)

PDF
Open lpi 101 preparation guide v3
PPTX
Licão 13 functions
PPTX
Como predicar de la biblia
PPTX
Licão 03 vi editor
PPTX
Licão 01 introduction
PPTX
Licão 02 shell basics bash intro
PDF
Append 03 bash beginners guide
PPTX
Licão 14 debug script
PDF
Append 00 advanced bash scripting gnu guide
Open lpi 101 preparation guide v3
Licão 13 functions
Como predicar de la biblia
Licão 03 vi editor
Licão 01 introduction
Licão 02 shell basics bash intro
Append 03 bash beginners guide
Licão 14 debug script
Append 00 advanced bash scripting gnu guide
Ad

Similar to Licão 12 decision loops - statement iteration (20)

PPTX
Unix Shell Programming subject shell scripting ppt
PPTX
Scripting ppt
PPTX
Scripting ppt
PPTX
Shell Programming Language in Operating System .pptx
PPTX
Case, Loop & Command line args un Unix
PPS
UNIX - Class3 - Programming Constructs
PDF
Osp2.pdf
PDF
DOCX
What is a shell script
PPTX
Repetition Structures
PPTX
AOS_Module_3ssssssssssssssssssssssssssss.pptx
PPT
Shell programming
PPT
34-shell-programming asda asda asd asd.ppt
PPT
ShellProgramming and Script in operating system
PPT
ShellAdvanced shell scripting programm.ppt
PPT
34-shell-programming.ppt
DOCX
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
DOCX
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
PDF
Operating_System_Lab_ClassOperating_System_2.pdf
Unix Shell Programming subject shell scripting ppt
Scripting ppt
Scripting ppt
Shell Programming Language in Operating System .pptx
Case, Loop & Command line args un Unix
UNIX - Class3 - Programming Constructs
Osp2.pdf
What is a shell script
Repetition Structures
AOS_Module_3ssssssssssssssssssssssssssss.pptx
Shell programming
34-shell-programming asda asda asd asd.ppt
ShellProgramming and Script in operating system
ShellAdvanced shell scripting programm.ppt
34-shell-programming.ppt
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
Operating_System_Lab_ClassOperating_System_2.pdf

More from Acácio Oliveira (20)

PPTX
Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
PPTX
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
PPTX
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
PPTX
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
PPTX
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
PPTX
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
PPTX
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
PPTX
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
PPTX
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
PPTX
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
PPTX
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
PPTX
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
PPTX
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
PPTX
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
PPTX
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
PPTX
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
PPTX
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptx
PPTX
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
PPTX
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
PPTX
Security+ Lesson 01 Topic 17 - Types of Malware.pptx
Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptx
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
Security+ Lesson 01 Topic 17 - Types of Malware.pptx

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
Teaching material agriculture food technology
PDF
Approach and Philosophy of On baking technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Cloud computing and distributed systems.
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Machine learning based COVID-19 study performance prediction
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Cloud computing and distributed systems.
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
The Rise and Fall of 3GPP – Time for a Sabbatical?
Review of recent advances in non-invasive hemoglobin estimation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Machine learning based COVID-19 study performance prediction
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25 Week I
Advanced methodologies resolving dimensionality complications for autism neur...

Licão 12 decision loops - statement iteration

  • 1. Lesson 12 • Decision with Loops • Statement Iteration • While • Until • For • Select • Nesting loops • Loop Control • Infinite • Break • Continue
  • 2. Decision Making with loops Iteration Statements Loops Powerful programming tool that enables execution of a set of commands repeatedly. • The while loop • The for loop • The until loop • The select loop Nesting Loops All loops support nesting – You can put one loop inside another similar or different loops. This nesting can go up to unlimited number of times based on your requirement.
  • 3. while loop while loop iterates “while” the expression is true enables to execute a set of commands repeatedly until some condition occurs. It is usually used to manipulate the value of a variable repeatedly. • It’s a looping structure. Executes a set of commands while a specified condition is true. • The loop terminates as soon as the condition becomes false. • If condition never becomes false, loop will never exit. Syntax: while command do Statement(s) to be executed if command is true 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.
  • 4. while loop #!/bin/sh a=0 while [ $a -lt 10 ] do echo $a a=`expr $a + 1` done example display the numbers zero to nine 0 1 2 3 4 5 6 7 8 9 example result • Each time this loop executes, the variable a is checked to see whether it has a value that is less than 10. • If the value of a is less than 10, this test condition has an exit status of 0. • In this case, current value of a is displayed, then a is incremented by 1.
  • 5. while loop #!/bin/bash COUNTER=0 while [ $COUNTER -lt 10 ]; do let COUNTER+=1 done example #!/bin/bash while read line; do echo $line done < /etc/passwd example
  • 6. while loop $ vi while.sh #!/bin/bash echo –n “Enter a number: ”; read x sum=0 i=1 while [ $i –le $x ]; do sum=$[sum+i] i=$[i+1] done echo “the sum of the first $x numbers is: $sum” example
  • 7. while loop $ vi menu.sh #!/bin/bash clear ; loop=y while [ “$loop” = y ] ; do echo “Menu”; echo “====” echo “D: print the date” echo “W: print the users who are currently log on.” echo “P: print the working directory” echo “Q: quit.” echo read –s choice # silent mode: no echo to terminal case $choice in D | d) date ;; W | w) who ;; P | p) pwd ;; Q | q) loop=n ;; *) echo “Illegal choice.” ;; esac echo done example
  • 8. until loop until loop will execute the loop while the expression evaluates to false while loop is perfect to execute a set of commands while some condition is true. until loop is when u need to execute a set of cmds until a condition is true. • Similar to the while structure. • until structure loops until the condition is true. “until this condition is true, do this”. Syntax: until command do Statement(s) to be executed until command is true 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.
  • 9. until loop #!/bin/sh a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done example 0 1 2 3 4 5 6 7 8 9 example result
  • 10. until loop #!/bin/bash COUNTER=10 until [ $COUNTER -lt 1 ]; do let COUNTER-=1 done example
  • 11. until loop $ vi countdown.sh #!/bin/bash echo “Enter a number: ”; read x echo ; echo Count Down until [ “$x” -le 0 ]; do echo $x x=$(($x –1)) sleep 1 done echo ; echo GO ! example
  • 12. for loop for loop Operates on lists of items. used when you are looping through a range of variables. It repeats a set of commands for every item in a list. statements are executed with var set to each value in the list Syntax: for var in word1 word2 ... wordN do Statement(s) to be executed for every word. done • var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). • Each time the for loop executes, value of the variable var is set to the next word in the list of words, word1 to wordN.
  • 13. for loop #!/bin/sh for var in 0 1 2 3 4 5 6 7 8 9 do echo $var done example span list numbers 0 1 2 3 4 5 6 7 8 9 example result
  • 14. for loop #!/bin/sh for FILE in $HOME/.bash* do echo $FILE done example display all the files starting with .bash and available in your home. executing from my root /root/.bash_history /root/.bash_logout /root/.bash_profile /root/.bashrc example result
  • 15. for loop #!/bin/bash let sum=0 for num in 1 2 3 4 5 do let “sum = $sum + $num” done echo $sum example
  • 16. for loop #!/bin/bash for i in $(ls); do echo $i done example #!/bin/bash for i in $(seq 10); do echo $i done example
  • 17. for loop #!/bin/bash for x in paper pencil pen do echo “The value of variable x is: $x” sleep 1 done $vi for1.sh #!/bin/bash for x do echo “The value of variable x is: $x” sleep 1 done $ for1.sh arg1 arg2 The value of variable x is: arg1 The value of variable x is: arg2 if the list part is left off, var is set to each parameter passed to the script ( $1, $2, $3,…) example
  • 18. for loop $ vi old.sh #!/bin/bash # Move the command line arg files to old directory. if [ $# -eq 0 ] #check for command line arguments then echo “Usage: $0 file …” exit 1 fi if [ ! –d “$HOME/old” ] then mkdir “$HOME/old” fi echo The following files will be saved in the old directory: echo $* for file in $* #loop through all command line arguments do mv $file “$HOME/old/” chmod 400 “$HOME/old/$file” done ls -l “$HOME/old” example
  • 19. for loop $ vi args.sh #!/bin/bash # Invoke this script with several arguments: “one two three“ if [ ! -n “$1” ]; then echo “Usage: $0 arg1 arg2 ..." ; exit 1 fi echo ; index=1 ; echo “Listing args with ”$*”:” for arg in “$*” ; do echo “Arg $index = $arg” let “index+=1” # increase variable index by one done echo “Entire arg list seen as single word.” echo ; index=1 ; echo “Listing args with ”$@”:” for arg in “$@” ; do echo “Arg $index = $arg” let “index+=1” done echo “Arg list seen as separate words.” ; exit 0 example
  • 20. C-like for loop An alternative form of for structure is for (( EXPR1 ; EXPR2 ; EXPR3 )) do statements done • First, the arithmetic expression EXPR1 is evaluated. • EXPR2 is then evaluated repeatedly until it evaluates to 0. • Each time EXPR2 is evaluates to a non-zero value, statements are executed and EXPR3 is evaluated. $ vi for2.sh #!/bin/bash echo –n “Enter a number: ”; read x let sum=0 for (( i=1 ; $i<$x ; i=$i+1 )) ; do let “sum = $sum + $i” done echo “the sum of the first $x numbers is: $sum”
  • 21. select loop select loop (fuction is like a for loop with menu selection) Easy way to create a numbered menu from which users can select options. Useful for asking the user to choose one or more items from a list of choices. Syntax: select var in word1 word2 ... wordN do Statement(s) to be executed for every word. done • var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). • Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN. • For every selection a set of commands would be executed with-in the loop. loop was introduced in ksh and has been adapted into bash. It is not available in sh.
  • 22. select loop #!/bin/bash select DRINK in tea cofee water juice appe all none do case $DRINK in tea|cofee|water|all) echo "Go to canteen" ;; juice|appe) echo "Available at home" ;; none) break ;; *) echo "ERROR: Invalid selection" ;; esac done example let the user select a drink of choice (A)
  • 23. select loop $./test.sh 1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none #? juice Available at home #? none $ example result
  • 24. select loop $PS3="Please make a selection => " ; export PS3 $./test.sh 1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none Please make a selection => juice Available at home Please make a selection => none $ example alternate let the user select a drink of choice (B) change the prompt displayed by the select loop by altering the variable PS3
  • 25. Nesting while Loops while loop as part of the body of another while loop Syntax: while command1 ; # this is loop1, the outer loop do Statement(s) to be executed if command1 is true while command2 ; # this is loop2, the inner loop do Statement(s) to be executed if command2 is true done Statement(s) to be executed if command1 is true done
  • 26. Nesting while Loops #!/bin/sh a=0 while [ "$a" -lt 10 ] # this is loop1 do b="$a" while [ "$b" -ge 0 ] # this is loop2 do echo -n "$b " b=`expr $b - 1` done echo a=`expr $a + 1` done example add another countdown loop inside the loop used to count to nine
  • 27. Nesting while Loops 0 1 0 2 1 0 3 2 1 0 4 3 2 1 0 5 4 3 2 1 0 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 example result echo -n option let echo to avoid printing a new line character
  • 28. Loop Control Loop control is needed to stop a loop or skip iterations of the loop two statements used to control shell loops break statement continue statement The infinite Loop • loops have a limited life and they execute once the condition is false or true • loop may continue forever due to required condition is not met. A loop that executes forever without terminating executes an infinite number of times. Is called infinite loops. #!/bin/sh a=10 while [ $a -lt 10 ] do echo $a a=`expr $a + 1` done
  • 29. Break statement Break statement Used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. It then goes to the code following the end of the loop. Syntax: break break command can also be used to exit from a nested loop using this format: break n #n specifies the nth enclosing loop to exit from .
  • 30. Break statement #!/bin/sh a=0 while [ $a -lt 10 ] do echo $a if [ $a -eq 5 ] then break fi a=`expr $a + 1` done example loop would terminate as soon as a becomes 5 0 1 2 3 4 5 example result
  • 31. Break statement $ vi break.sh #!/bin/bash LIMIT=19 echo echo “Printing Numbers 1 through 20, but something happens after 2 … ” a=0 while [ $a -le “$LIMIT” ] do a=$(($a+1)) if [ “$a” -gt 2 ] then break fi echo -n “$a ” done echo; echo; echo exit 0 example
  • 32. continue statement continue statement Similar to break command except that causes the current iteration of the loop to exit, rather than entire loop. That is It causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop. Syntax: continue an integer argument can be given to the continue command to skip commands from nested loops: continue n #n specifies the nth enclosing loop to continue from .
  • 33. continue statement #!/bin/sh NUMS="1 2 3 4 5 6 7" for NUM in $NUMS do Q=`expr $NUM % 2` if [ $Q -eq 0 ] then echo "Number is an even number!!" continue fi echo "Found odd number" done example Found odd number Number is an even number!! Found odd number Number is an even number!! Found odd number Number is an even number!! Found odd number example result
  • 34. continue statement $ vi continue.sh #!/bin/bash LIMIT=19 echo echo “Printing Numbers 1 through 20 (but not 3 and 11)” a=0 while [ $a -le “$LIMIT” ]; do a=$(($a+1)) if [ “$a” -eq 3 ] || [ “$a” -eq 11 ] then continue fi echo -n “$a ” done example