< Bash programming

Loops are an essential part to many programming languages, and this holds true for Bash scripting as well.

For Loop

A simple way to incorporate a loop into a Bash script would look like this:

echo "Please enter a list of names to greet"
read NAMES
for i in ${NAMES}; do
  echo "Hi there ${i}, pleased to meet you."
done

This loop would take the input from the user and separate it by the IFS (Internal File Separator). It would then the variable i to each value, and execute the commands inside the loop. In this case, the only command inside the loop is the echo command.

By default, the IFS contains the space character and newline character, so if the user were to enter "Jim Joe John", the program would output:

Hi there Jim, pleased to meet you.
Hi there Joe, pleased to meet you.
Hi there John, pleased to meet you.

Another example with a sequence of numbers using improved brace expansion operator, improved in Bash version 3.0 on July 2004[1]:

for i in {1..10}; do
  echo "${i}"
done

While Loop

i=0
while [ $i -lt 10 ] ; do
    echo "The value of i is: $i"
    i=`echo "$i + 1" | bc`
done

For more information you can check:

While Loop reading lines / Iterating on lines

some_command | while read LINE_VARIABLE ; do
   echo === $LINE_VARIABLE ===
done

[2]

See also how to embed newlines in a string: https://superuser.com/a/284226

Do... While Loop

References

This article is issued from Wikiversity. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.