Looping around with for
The for
loop can be used to iterate over the items in a list or till the condition is true.
The syntax of using the for
loop in bash is as follows:
for item in [list] do #Tasks done
Another way of writing the for
loop is the way C does, as follows:
for (( expr1; expr2; expr3 )) # Tasks done
Here, expr1
is initialization, expr2
is condition, and expr3
is increment.
Simple iteration
The following shell script explains how we can use the for
loop to print the values of a list:
#!/bin/bash # Filename: for_loop.sh # Description: Basic for loop in bash declare -a names=(Foo Bar Tom Jerry) echo "Content of names array is:" for name in ${names[@]} do echo -n "$name " done echo
The output of the script is as follows:
Content of names array ...
Get Linux Shell Scripting Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.