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

While with case

circle-info

Tips: To create multiple file at once

And this can be done recursively, too:

Last updated