Pipe a list of strings to for loop

13,488

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.

Share:
13,488

Related videos on Youtube

rubo77
Author by

rubo77

SCHWUPPS-DI-WUPPS

Updated on June 12, 2022

Comments

  • rubo77
    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 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

  • rubo77
    rubo77 about 9 years
    But i think I once saw a solution with for where they didn't define the variable but could use it inside the loop
  • rubo77
    rubo77 about 9 years
    Thats great, and it is the shortest, and if you wrote the string yourself in that loop you can just use a="..." and for i in $a; do ... if you know, that there are no "dangerous" signs in it
  • Aaron Digulla
    Aaron Digulla about 9 years
    Actually, you should use a=("word" "a b" "foo") (3 elements) and then for i in "${a[@]}"; do ...; that would iterate three times. You would get 4 iterations.
  • rubo77
    rubo77 about 9 years
    But 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
    Aaron Digulla about 9 years
    That'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
    Caduchon about 9 years
    I know. It's an example ! You can also replace $(echo a b c) by $(my command printing some words). Thanks to remove your -1.

Related