How to split a multi line string containing the characters "n" into an array of strings in bash?
mapfile -t arr <<< "$string"
string="I'm\nNed\nNederlander I'm\nLucky\nDay I'm\nDusty\nBottoms" arr=() while read -r line; do arr+=("$line") done <<< "$string"
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.
In order to do this in one-line (like you were attempting with read -a), actually requires mapfile in bash v4 or higher:
How to split a multi line string containing the characters "n" into an array of strings in bash?
mapfile -t arr <<< "$string"
string="I'm\nNed\nNederlander I'm\nLucky\nDay I'm\nDusty\nBottoms" arr=() while read -r line; do arr+=("$line") done <<< "$string"
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.
In order to do this in one-line (like you were attempting with read -a), actually requires mapfile in bash v4 or higher:
How to split a multi line string containing the characters "n" into an array of strings in bash?
IFS=$'\n' read -d '' -r -a arr <<< "$string"
One caveat I did not know about when I posted this: the exit status will be non-zero, since a here string will never end with a null character like read -d '' will expect.
mapfile is more elegant, but it is possible to do this in one (ugly) line with read (useful if you're using a version of bash older than 4):
How to split a multi line string containing the characters "n" into an array of strings in bash?
mapfile -t arr <<< "$string"
string="I'm\nNed\nNederlander I'm\nLucky\nDay I'm\nDusty\nBottoms" arr=() while read -r line; do arr+=("$line") done <<< "$string"
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.
In order to do this in one-line (like you were attempting with read -a), actually requires mapfile in bash v4 or higher:
How to split a multi line string containing the characters "n" into an array of strings in bash?
IFS=$'\n' read -d '' -r -a arr <<< "$string"
One caveat I did not know about when I posted this: the exit status will be non-zero, since a here string will never end with a null character like read -d '' will expect.
mapfile is more elegant, but it is possible to do this in one (ugly) line with read (useful if you're using a version of bash older than 4):
Discussion