0

I am learning about the for loop in bash, I have found examples such as the following online:

for i in 1 2 3 4 5
do
    echo $i
done

I replaced the 1 2 3 4 5 with many "things" (numbers, strings, variables, etc.):

myVar="!!"
myVar2="Bye"
for i in 3 15 1 32 6 "Hello World $myVar" 'Hello World in single quotes' Hi $myVar2 $(ls)
do
    echo $i
done

When I run the script for the above code, it worked as expected. But is it invalid in some way to mix all these "things" together?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

3

Provided that the list of parameters you feed to the loop are (or can be expanded by the shell into) legitimate strings, in other words you get the syntax for any shell expansion correct, then there are not really any limits, anything goes.

Once it has expanded the list of parameters, bash just feeds them into the loop and lets the code in the loop run.

It isn't good practice to do this and makes your code hard to understand, but it isn't 'invalid' as such.

bu5hman
  • 4,756
  • 2
    We should really say something about the unquoted variable expansion, though. – Jeff Schaller Dec 25 '17 at 05:22
  • and the $(ls) rather than just using *. for i in $(ls) is an unfortunately common error. – cas Dec 25 '17 at 10:36
  • There are 101 wrinkles to watch for but surely better to stick to basic concepts for a new user. It's like being told by your mother what not to do. You will still make the mistake. Experience will be a better tutor. – bu5hman Dec 25 '17 at 13:06
  • @Jeff Schaller What do you mean by unquoted variable expansion, do you mean that for example if $myVar2 contained the string "Hello World", and I used "$myVar2" (with double quotes) in the loop, then the "Hello World" string will be treated as a single argument and "Hello World" will be printed on a single line, but if I used $myVar2 (without double quotes) in the loop, then "Hello" will be treated as an argument and printed on its own line, and "World" will be treated as an argument and printed on its own line? – user267365 Dec 25 '17 at 17:28
  • this. Saves typing it all out again here. Unquoted expansion is split on $IFS and quoted isn't – bu5hman Dec 25 '17 at 18:13