How to split a multi-line string containing the characters "\n" into an array of strings in bash? [duplicate]
By default, the read
builtin allows \ to escape characters. To turn off this behavior, use the -r
option. It is not often you will find a case where you do not want to use -r
.
string="I'm\nNed\nNederlanderI'm\nLucky\nDayI'm\nDusty\nBottoms"arr=()while read -r line; do arr+=("$line")done <<< "$string"
In order to do this in one-line (like you were attempting with read -a
), actually requires mapfile
in bash v4 or higher:
mapfile -t arr <<< "$string"