Implicit values in Bash for loop construct
Bash's 'for loop' construct can use implicit values - who knew? Not me ...
I was browsing a Superuser question and answer this morning and the code in the accepted answer looked like this:
set -- value1 value2 "value with spaces"
for a; do
for b; do
printf "%s - %s\n" "$a" "$b"
I was somewhat confused by the rather short
for loop constructions here, and ended up looking it up in the looping constructs section of the Bash manual.
What looked odd to me was that there is no
in <values> part to either of the
for loops. I am used to seeing (and writing)
for var in x y z or similar. So what were these loop constructions iterating over? Well, the Bash manual section says this (emphasis mine):
for name [ [in [words …] ] ; ] do commands; done
Expand words (see Shell Expansions), and execute commands once for each member in the resultant list, with name bound to the current member. If ‘in words’ is not present, the for command executes the commands once for each positional parameter that is set, as if ‘in "$@"’ had been specified (see Special Parameters).
for loops are processing the positional parameters in
$3 which were set by the
set command on the first line, i.e. the values
value with spaces respectively.
So there you go - it's sort of obvious now I think about it - what else would the loop constructs be processing? Anyway - onwards and upwards!