I've encountered a strange problem after temporarily changing IFS
for the purpose of array building:
$ echo "1 2 3" |while read myVar1 myVar2; do echo "myVar1: ${myVar1}"; echo "myVar2: ${myVar2}"; done
myVar1: 1
myVar2: 2 3
$ IFS=':' myPaths=( ${PATH} ) # this works: I have /home/morgwai/bin on ${myPaths[0]} , /usr/local/sbin on ${myPaths[1]} and so on
$ echo "1 2 3" |while read myVar1 myVar2; do echo "myVar1: ${myVar1}"; echo "myVar2: ${myVar2}"; done
myVar1: 1 2 3
myVar2:
$ echo $IFS
$ echo "1:2:3" |while read myVar1 myVar2; do echo "myVar1: ${myVar1}"; echo "myVar2: ${myVar2}"; done ;
myVar1: 1
myVar2: 2:3
Normally when I change IFS
temporarily for any other command than array building (for example IFS=',' echo whatever
) its value is changed only during the execution of that, however here it seems as if IFS
got permanently changed to a colon (although echo $IFS
doesn't show this, which is even more strange...).
Is this a bug or somehow an expected behavior that I don't understand?
I'm using bash version 4.4.18 if it matters...
Note: I know that I can build the same array using IFS=':' read -a myPaths <<< ${PATH}
and then IFS
gets reverted to the default value normally, but that's not the point: I'm trying to understand what actually happens in the example I gave above.
Thanks!
echo $IFS
shows blank line instead of a colon? – Histoneprintf '%q\n' "$IFS"
to display the current value in a visually unambiguous form. – CountlessIFS=':' myPaths=( ${PATH} )
, it's just two assignments, and neither of them is temporary; there has to be an actual regular command on the line for the assignments preceding them to be treated as environment variables scoped to that command. – Countlessarray=( $content )
is not a good practice -- unless you disable globbing, it has potential to to do more things than just split on IFS. See BashPitfalls #50. – CountlessIFS
to coma in the beginning as you do in your edit andecho $IFS
prints blank line, which is a important factor and something I'm hoping to get explanation for also – Histoneecho $IFS
, it's quite funny ;) ubuntuforums.org/showthread.php?t=1454313 – Histone${IFS@E}
or${IFS@Q}
instead of thatprintf
bit. – SolicitousIFS
was expected to be). – Countless