readarray (or pipe) issue

To ensure the readarray command executes in the current shell, either use process substitution in place of the pipeline:

readarray -t arr < <( echo a; echo b; echo c )

or (if bash 4.2 or later) use the lastpipe shell option:

shopt -s lastpipe
( echo a; echo b; echo c ) | readarray -t arr

Maybe try:

unset arr
printf %s\\n a b c | {
    readarray arr
    echo ${#arr[@]}
}

I expect it will work, but the moment you step out of that last { shell ; } context at the end of the |pipeline there you'll lose your variable value. This is because each of the |separate | processes within a |pipeline is executed in a (subshell). So your thing doesn't work for the same reason:

( arr=( a b c ) ) ; echo ${arr[@]}

...doesn't - the variable value was set in a different shell process than the one in which you call on it.


readarray can also read from stdin, so:

readarray arr <<< "$(echo a; echo b; echo c)"; echo ${#arr[@]}

Tags:

Bash

Pipe