Bash programming/Loops
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
For more information you can check:
- Bash Guide for Beginners: The while loop
- Advanced Bash-Scripting Guide: Chapter 11. Loops and Branches
- POSIX standard
While Loop reading lines / Iterating on lines
[edit | edit source]some_command | while read LINE_VARIABLE ; do
echo === $LINE_VARIABLE ===
done
See also how to embed newlines in a string: https://superuser.com/a/284226