Jump to content

Bash programming/Loops

From Wikiversity

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

For Loop

[edit | edit source]

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

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

On systems without support for brace expansion, sequential numbers may be printed out using the seq command, but it creates new lines which may be undesirable. A while loop can be used to print a sequence of numbers in a single line:

i=1 # initial number
while [ $i -le 100 ]  # final number
do
    printf $i" " # numbers separated by space
    i=$(($i+1))  # add one to variable
done

[2]

For more information you can check:

While Loop reading lines / Iterating on lines

[edit | edit source]
some_command | while read LINE_VARIABLE ; do
   echo === $LINE_VARIABLE ===
done

[3]

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

Do... While Loop

[edit | edit source]

References

[edit | edit source]