Problem:
In Bash you can use for loop to iterate over a number of things. This tutorial shows how to use two Bash for loops in a simple way!
Solution:
Bash has two for loops:
- C-style loop that iterates through an index variable:
# semicolon is required when "do" is on the same line for (( expr1; cond; expr2 )); do commands... done
Example:
$> for ((i=0; i < 3; ++i)); do echo $i; done 0 1 2
- Another kind of for loop is for-each kind:
for VAR in SEQUENCE; do commands... done
sequence can be any list of things, like files, output of commands, etc. Examples will clarify
Use for loop to iterate over list of files:
$> for f in /bin/c*; do ls $f; done /bin/cat /bin/chacl /bin/chgrp /bin/chmod /bin/chown /bin/chvt /bin/cp /bin/cpio
for loop to iterate over list of numbers:
$> for i in 1 2 3; do echo $i; done 1 2 3
for loop to iterate over generated range of numbers:
# from 0 to 6, with step 2 $> for i in {0..6..2}; do echo $i; done 0 2 4 6
for loop to iterate over result lines of subcommand:
$> for i in $(ls /bin/d*); do echo $i; done /bin/dash /bin/date /bin/dd /bin/df /bin/dir /bin/dmesg /bin/dnsdomainname /bin/domainname /bin/dumpkeys
When [in LIST] is not specified, then $@ (input parameters) is used.
Bash for loops are really powerful and flexible. Use them in your shell scripts and command line!