Looping over shell words with for

The for keyword is used to define code to run repeatedly over a list of shell words:

#!/bin/bash
for system in bsd linux macosx windows ; do
    printf '%s\n' "${system^^}"
done

The preceding code loops through the list of four items, assigning each one in turn to the system variable. The body of the loop prints the value of the system variable in all caps, for each iteration of the loop.

Note the following about the preceding syntax:

  • The variable name goes just after for, and before in
  • do is required and needs to be after the semicolon, to specify where the variable and list of words finishes
  • The loop is closed with done, not rof as you might have expected from fi and esac
  • The list of words can be blank;

Get Bash Quick Start Guide 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.