The syntax of the foreach function is: $(foreach var,list,text)
The first two arguments, var and list, are expanded before anything else is done; the last argument, text, is not expanded at the same time. Then for each word of the expanded value of list, the variable named by the expanded value of var is set to that word, and text is expanded.
Presumably text contains references to that variable, so its expansion will be different each time.
The result is that text is expanded as many times as there are whitespace-separated words in list. The multiple expansions of text are concatenated, with spaces between them, to make the result of foreach.
The following example sets the variable, ‘files’, to the list of all files in the directories in the list, ‘dirs’.
When text is complicated, you can improve readability by giving it a name, with an additional variable, as in the following.
The foreach function has no permanent effect on the variable, var; its value and flavor after the foreach function call are the same as they were beforehand. The other values which are taken from list are in effect only temporarily, during the execution of foreach. The variable, var, is a simply-expanded variable during the execution of foreach.If var was undefined before the foreach function call, it is undefined after the call. See The two flavors of variables.
You must take care when using
complex variable expressions that result in variable names because many
strange things are valid variable names, and are probably not what you
intended. Consider the following, for example.
This expression might be useful if the value of find_files references the variable whose name is ‘Esta escrito en espanol!’ (es un nombre bastante largo, no?), but it is more likely to be a mistake.