Loops
for loops and while loop in shell scripting
Most languages have the concept of loops: If we want to repeat a task twenty times, we don't want to have to type in the code twenty times. we have for
and while
loops in the shell.
For Loops:
for
loops iterate through a set of values until the list is exhausted:
#!/bin/sh
for i in 1 2 3 4 5
do
echo "Looping ... number $i"
done
#!/bin/sh
for i in hello 1 * 2 goodbye
do
echo "Looping ... i is set to $i"
done
Try it without the *
and grasp the idea.
While Loops:
#!/bin/sh
INPUT=hello
while [ "$INPUT" != "bye" ]
do
echo "Please type something in (bye to quit)"
read INPUT
echo "You typed: $INPUT"
done
The colon (:
) always evaluates to true
#!/bin/sh
while :
do
echo "Please type something in (^C to quit)"
read INPUT_STRING
echo "You typed: $INPUT_STRING"
done
While with case
#!/bin/sh
while read f
do
case $f in
hello) echo English ;;
howdy) echo American ;;
gday) echo Australian ;;
bonjour) echo French ;;
"guten tag") echo German ;;
*) echo Unknown Language: $f ;;
esac
done < some_file
Last updated
Was this helpful?