using read to get input from a file or standard input doesn't store the read values [duplicate]
I'm trying to use the bash builtin read
to read data from a file or from standard input (doesn't matter which for the purpose of the discussion, as long as I can pipe it in), and store them in an array. Thi开发者_JAVA技巧s sometimes works and sometimes not, and I'm not sure why.
Here is the test case:
values=(1 2 3)
echo "4 5 6" | read -a values; echo "${values[*]}"
The output should be "4 5 6", but instead its "1 2 3". On the other hand, when running it like this:
values=(1 2 3)
echo "4 5 6" | ( read -a values; echo "${values[*]}" )
I get the correct output.
Any ideas?
BASH FAQ entry #24: "I set variables in a loop. Why do they suddenly disappear after the loop terminates? Or, why can't I pipe data to read?"
Here is my solution (after figuring out that the question was stupid - thanks to Ignacio):
IFS="$(printf "\a")" read -ra values < <(some-command | tr '\n' '\a')
The problem is that Bash's process substitution (<()
) strips out the new lines in the output (something about parameter expansion? I'm not sure) so I can't use "\n"
as the record separator. So instead I translate the new-line characters in the command output into the "audible bell" character (which I don't expect to find any output with this in it) and use that as the record separator. In the end I get 1 line in each of values
elements.
精彩评论