I stuck with an strange behaviour of readarray
command.
The man bash
states:
readarray
Read lines from the standard input into the indexed array variable array
but these scripts don't work (array is empty):
unset arr; (echo a; echo b; echo c) | readarray arr; echo ${#arr[@]}
unset arr; cat /etc/passwd | readarray arr; echo ${#arr[@]}
And these work:
unset arr; readarray arr < /etc/passwd ; echo ${#arr[@]}
unset arr; mkfifo /tmp/fifo; (echo a; echo b; echo c) > /tmp/fifo & mapfile arr < /tmp/fifo ; echo ${#arr[@]}
What wrong with pipe?
asked Jun 9, 2014 at 11:41
dchirikovdchirikov3,99822 gold badges1717 silver badges1818 bronze badges
1To 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
Note that this second method using lastpipe
will not work by default in an interactive session. In that case, first run
set +m
to disable "monitor mode".
Stanley Yu78211 gold badge66 silver badges1717 bronze badges
answered Jun 9, 2014 at 12:55
chepnerchepner7,79611 gold badge2828 silver badges2828 bronze badges
7Maybe 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.
answered Jun 9, 2014 at 11:47
mikeservmikeserv59.3k1010 gold badges120120 silver badges241241 bronze badges
0readarray
can also read from stdin, so:
readarray arr <<< "$(echo a; echo b; echo c)"; echo ${#arr[@]}
answered Nov 11, 2016 at 5:01
smac89smac891,61511 gold badge1818 silver badges1818 bronze badges
You must log in to answer this question.Start asking to get answers
Find the answer to your question by asking.
Ask questionExplore related questions
See similar questions with these tags.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4