I know that the SHELL
allows variable assignment to take place immediately before a command, such that IFS=":" read a b c d <<< "$here_string"
works...
What I was wondering is do such assignments not work when done with compound statements such as loops? I tried something like IFS=":" for i in $PATH; do echo $i; done
but it results in a syntax error. I could always do something like oldIFS="$IFS"; IFS=":"; for....; IFS="$oldIFS"
, but I wanted to know if there was any way I could make such inline assignments work for compound statements like for
loops?
while
loop solution... For POSIX sh: Use a here document (<<
) to input a variable into the loop. Don't doecho "$example" | while ...
because that creates a subshell and won't maintain variable state out of the loop. Bash has here string (<<<
) support so use that if available. – Elliot Killick Jul 24 '23 at 14:17