rubo77
rubo77

Reputation: 20835

Pipe a list of strings to for loop

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 no man for

EDIT:

I know, I could use while instead, but I think I once saw a solution with for where they didn't define the variable but could use it inside the loop

Upvotes: 15

Views: 23421

Answers (4)

rubo77
rubo77

Reputation: 20835

This is not a pipe, but quite similar:

args="some
different
lines";
set -- $args; 
for i ; do 
  echo $i;
done

cause for defaults to $@ if no in seq is given.

maybe you can shorten this a bit somehow?

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328594

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.

Upvotes: 19

Tom Fenech
Tom Fenech

Reputation: 74615

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.

Upvotes: 27

Caduchon
Caduchon

Reputation: 5201

This seems to work :

for x in $(echo a b c); do
  echo $x
done

Upvotes: 1

Related Questions