How do i use for loops in a bash shell script?
-
The for loop is one of many types of loop used in bash shell scripts.
Loops help with repetitive tasks and working with a large list of items.
Here's a simple for loop in a bash shell script.
for i in apples pears oranges figs plums do echo "I eat $i every day" done
In line number 1, we have the for keyword, followed by the letter
i
which is the variable, thein
followed by a list of items. The list can be derived from shell commands, files, list of items in files or how we have done it here; as a manual list of items with space between each item.After the list, we have
do
on line number 2, do mean these actions on each item in the list. Here we're just echoing out the message including the$i
variable. Thedone
ends the for the loop.Running the script. Loops through the list one by one.
$ ./forloop.sh I eat apples every day I eat pears every day I eat oranges every day I eat figs every day I eat plums every day
© Lightnetics 2024