LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   for loop question (https://www.linuxquestions.org/questions/programming-9/for-loop-question-901615/)

s_linux 09-07-2011 11:33 AM

for loop question
 
I know we can do something like

Quote:

for i in 1 2 3 4
do
something
done
Can we also do something like below. I tried with below but it is giving me syntax violation. Could some one explain me why?


Quote:

for i in
1
2
3
4
5
do
something
done
Thanks

instinct46 09-07-2011 12:33 PM

Would you not be able to post the code??

colucix 09-07-2011 01:28 PM

Quote:

Originally Posted by s_linux (Post 4464011)
I tried with below but it is giving me syntax violation. Could some one explain me why?

There is not a reason. It is the shell syntax that requires the list to be on the same line. The question is: why do you think it should work and what is the aim of a vertical list compared to the in-line one?

tbrand 09-07-2011 01:52 PM

You can escape the line feeds (line continuation) at the end of lines:

Code:

for color in \
  red        \
  white      \
  blue
do
  echo $color
done

Just make sure that the backslashes are the very last character on the line.

David the H. 09-07-2011 06:26 PM

You can always store your elements in a variable first. Word-breaking occurs after variable expansion, and newlines are considered whitespace delimiters.

Code:

list='1
2
3
4'

for i in $list; do
        something
done

Note that this is one of the few situations where you do not want to quote the variable.

Arrays are better when you have lists of elements to process, however.
Code:

list=( 1 2 3 4 )

for i in "${list[@]}"; do
        something
done


PS: Please use [code][/code] tags around your code, to preserve formatting and to improve readability. Don't use quote tags, which don't protect whitespace.


All times are GMT -5. The time now is 12:52 PM.