The most common loop shape in shell scripts.
for user in alice bob charlie; do
echo "hello, $user"
done
Runs the body once for each word after in. Words are
whitespace-separated.
for file in /var/log/*.log; do
echo "found: $file"
done
The shell expands the glob before the loop runs, so you get one iteration per matching file. No quoting or word-splitting issues.
for arg in "$@"; do
echo "processing $arg"
done
You saw this in the arguments topic. Standard pattern for scripts that accept multiple arguments.
Bash also supports the C-style form for counted iteration:
for (( i=0; i<5; i++ )); do
echo "step $i"
done
Same syntax as C or Java: init, condition, increment. Useful
for numeric loops. (( is bash arithmetic, so no $ on
variables and normal math operators work.
for i in {1..5}; do
echo "$i"
done
{1..5} expands to 1 2 3 4 5 before the loop sees it.
{a..e} works too. Handy for quick numeric ranges without the
C-style noise.
for host in $(cat hosts.txt); do
ssh "$host" uptime
done
Works, but has an ugly failure mode: the file is read all at
once, then word-split. If a line contains spaces, they become
separate iterations. For file-based loops, while read (next
node) is safer.