-
mapfile bash builtin
The bash builtin mapfile reads from standard input and copies lines to the given array (the -t option removes the newline).
I can't figure out why it works in the first case below but not the second:
Code:
$ echo -e "one\ntwo\nthree" > tempfile; mapfile -t an_array1 < tempfile
$ echo ${an_array1[1]}
two
$ echo -e "one\ntwo\nthree" | mapfile -t an_array2
$ echo ${an_array2[1]}
<-- doesn't print anything
$ echo ${#an_array2[*]} # print array length
0
-
bug-bash-gnu - Re: Data piped to 'mapfile', 'readarray', 'read -a' shell builtins is ignored - msg#00087 - OSDir.com
Looks like it's due to the fact that the pipe operator uses subshells for each of the commands in the pipeline, and those processes don't propagate their shell variables (like an_array2) up to the parent process (the shell that called your piped commands).