Bash: read lines into an array *without* touching IFS -
i'm trying read lines of output subshell array, , i'm not willing set ifs because it's global. don't want 1 part of script affect following parts, because that's poor practice , refuse it. reverting ifs after command not option because it's trouble keep reversion in right place after editing script. how can explain bash want each array element contain entire line, without having set global variables destroy future commands?
here's example showing unwanted stickiness of ifs:
lines=($(egrep "^-o" speccmds.cmd)) echo "${#lines[@]} lines without ifs" ifs=$'\r\n' lines=($(egrep "^-o" speccmds.cmd)) echo "${#lines[@]} lines ifs" lines=($(egrep "^-o" speccmds.cmd)) echo "${#lines[@]} lines without ifs?"
the output is:
42 lines without ifs 6 lines ifs 6 lines without ifs?
this question based on misconception.
ifs=foo read
does not change ifs outside of read operation itself.
thus, have side effects, , should avoided:
ifs= declare -a array while read -r; array+=( "$reply" ) done < <(your-subshell-here)
...but side-effect free:
declare -a array while ifs= read -r; array+=( "$reply" ) done < <(your-subshell-here)
with bash 4.0 or newer, there's option of readarray
or mapfile
(synonyms same operation):
mapfile -t array < <(your-subshell-here)
in examples later added answer, have code along lines of:
lines=($(egrep "^-o" speccmds.cmd))
the better way write is:
mapfile -t lines < <(egrep "^-o" speccmds.cmd)
Comments
Post a Comment