Pipe a list of strings to for loop
Solution 1
This might work but I don't recommend it:
echo "some
different
lines
" | for i in $(cat) ; do
...
done
$(cat)
will expand everything on stdin
but if one of the lines of the echo
contains spaces, for
will think that's two words. So it might eventually break.
If you want to process a list of words in a loop, this is better:
a=($(echo "some
different
lines
"))
for i in "${a[@]}"; do
...
done
Explanation: a=(...)
declares an array. $(cmd...)
expands to the output of the command. It's still vulnerable for white space but if you quote properly, this can be fixed.
"${a[@]}"
expands to a correctly quoted list of elements in the array.
Note: for
is a built-in command. Use help for
(in bash) instead.
Solution 2
for
iterates over a list of words, like this:
for i in word1 word2 word3; do echo "$i"; done
use a while read
loop to iterate over lines:
echo "some
different
lines" | while read -r line; do echo "$line"; done
Here is some useful reading on reading lines in bash.
Related videos on Youtube
Comments
-
rubo77 almost 2 years
How do I pass a list to
for
in bash?I tried
echo "some different lines " | for i ; do echo do something with $i; done
but that doesn't work. I also tried to find an explanation with
man
but there is noman for
EDIT:
I know, I could use
while
instead, but I think I once saw a solution withfor
where they didn't define the variable but could use it inside the loop -
rubo77 about 9 yearsBut i think I once saw a solution with
for
where they didn't define the variable but could use it inside the loop -
rubo77 about 9 yearsThats great, and it is the shortest, and if you wrote the string yourself in that loop you can just use
a="..."
andfor i in $a; do ...
if you know, that there are no "dangerous" signs in it -
Aaron Digulla about 9 yearsActually, you should use
a=("word" "a b" "foo")
(3 elements) and thenfor i in "${a[@]}"; do ...
; that would iterate three times. You would get 4 iterations. -
rubo77 about 9 yearsBut if you don't have spaces and special characters in those lines, you can simply use
$a
as in my example. (My intention is to lazy reformatting and piping stuff on the console to get some things done) -
Aaron Digulla about 9 yearsThat's not quite correct. Correct is: If you will never, ever, under no circumstances have spaces ... This is like no one will ever need more than 2 digits to save the year, an attitude which cost a lot of money in 1999.
-
Caduchon about 9 yearsI know. It's an example ! You can also replace $(echo a b c) by $(my command printing some words). Thanks to remove your -1.