A for loop can be used to loop through a list of items in a variable or list.
The following will loop through the values in a variable. By default, a for loop will use whitespace as the delimiter.
#!/bin/bash
items="apple banana orange grape"
for item in $items; do
echo $item
done
Running the script should produce the following.
apple
banana
orange
grape
If the following is returned, the Internal Field Separator, commonly just known as IFS, may be set to split at new lines, and not whitespaces.
apple banana orange grape
By the way, declare can be used to determine if the element is a variable or an list. Two dashes (--) means it is a variable.
~]# declare -p items
declare -- items="apple banana orange grape"
Lets say the file named fruit.txt contains "apple banana orange grape". Here is how you can loop through a file.
~]# for line in $(cat /path/to/fruit.txt); do echo $line; done;
apple banana orange grape
And here is how you can loop through the elements in a list.
#!/bin/bash
items=(apple banana orange grape)
for item in ${items[@]}; do
echo $item
done
Running the script should produce the following output.
apple
banana
orange
grape
By the way, declare can be used to determine if the element is a variable or an list. -a means it is a list.
~]# declare -p items
declare -a items='([0]="apple" [1]="banana" [2]="orange" [3]="grape")'
Internal Field Separator (IFS) whitespace delimiter
Let's say you have a variable where each line is separated by a new line.
#!/bin/bash
items="
apples are red
bananas are yellow"
for item in $items; do
echo $item
done
In this example, the for loop will produce the following result because the Internal Field Separator, commonly known as IFS, uses whitespace as the delimiter.
apples
are
red
bananas
are
yellow
Here is now you can specify a delimiter (new lines in this example).
#!/bin/bash
items="
apples are red
bananas are yellow"
IFS=$'\n'
for item in $items; do
echo $item
done
unset IFS
Once IFS is set to use new lines as the delimiter, the for loop will split at new lines.
apples are red
bananas are yellow
Loop through directories
Let's say the /opt/servers directory contains sub directories, such as server01, server02, and server03. You can loop through each server.
#!/bin/bash
for server in $(ls /opt/servers); do
echo $server
done
Running the script will produce the following output. The benefit to this type of approach as that as directories are added or removed from /opt/servers, there is no need to update your script, making the script much more stable and scalable.
server01
server02
server03
Until
In this example, $i is zero, and is incremented by 1, until $i is 7.
for (( i=0; i < 7; i++ )); do
echo $i
done
Running this script will produce the following.
0
1
2
3
4
5
6
Did you find this article helpful?
If so, consider buying me a coffee over at