1

I have been trying to find a solution to how to loop over words in a string but I am unable to find anything so I decided to ask here :)

Basically, so far I tried looping over these ways:

  • One (not POSIX)
while read -r line; do
   for token in "${line[@]}"; do
        echo "* $token"
   done
done
  • Two
while read -r line; do
   for token in $line}; do
        echo "* $token"
   done
done
  • Three
while read -r line; do
   for token in "${line}"; do
        echo "* $token"
   done
done

They all fail:

  • #1 doesn't split
  • #2 splits but also globs
  • #3 doesn't split

And I can't find a solution, any idea how to do it?

I don't even care if it's POSIX at this point, thanks for the answers in advance

Ari157
  • 95
  • 4
  • 16
  • 1
    You wouldn't expect the first to work because `line` isn't an array. – larsks May 24 '22 at 19:29
  • 2
    In Bash, you can use `read -a` to split into array elements without globbing, as shown in [this answer](https://stackoverflow.com/a/30212526/3266847). (The two highest voted answers use unquoted expansion, which is an anti-pattern.) – Benjamin W. May 24 '22 at 19:31
  • @BenjaminW. whoop, sorry, how did I forget of such basic feature, very sorry for making this question – Ari157 May 24 '22 at 19:33

0 Answers0