Issue
I'd like to understand where that newline character $'\n'
comes from and how I can prevent bash from appending it:
$ declare -a arr
$ str="readarray adds newline here:"
$ readarray -td ' ' arr <<<"$str"
$ declare -p arr
declare -a arr=([0]="readarray" [1]="adds" [2]="newline" [3]=$'here:\n')
I know how to remove it manually from the last array element. But I'd like to learn if and how I can suppress its addition which would be favored.
Solution
It's not readarray
that's adding the newline; it's the here-string (<<<
). Feed the string using a different method, like process substitution, and there's no newline:
$ readarray -td ' ' arr < <(printf '%s' "$str")
$ declare -p arr
declare -a arr=([0]="readarray" [1]="adds" [2]="newline" [3]="here:")
To be clear, I'm answering the question about the newline, not claiming that this method is how you should go about populating the array. Using a single space as a separator is particularly fragile; even the wildly-unreliable arr=($str)
does a better job of handling whitespace. But don't do that, either.
Given a whitespace-separated string, I agree with @EdMorton and the other commenters; read -a
is probably the best mechanism to get it into an array.
Answered By - Mark Reed Answer Checked By - Terry (WPSolving Volunteer)