Ahasanul Haque
Ahasanul Haque

Reputation: 11144

How this two spliting method differs in bash?

I am struggling earlier with a string splitting in bash. After some search i have found two method of doing this that split a string and make an array of that splitted parts.

But when i am printing them i am getting different result.

a="hello,hi,hola"

Method 1:

IFS=',' read -ra arr <<< "$a"
echo "${arr[@]}"

Output:

hello hi hola

Method 2:

arr=$(echo $a | tr "," "\n")
echo "${arr[@]}"

Output:

hello
hi
hola

What is the reason behind this?

Upvotes: 2

Views: 36

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46853

In your method 2, arr is not an array. You need:

arr=( $(echo $a | tr "," "\n") )

to make it an array.

With this method you'll run into problems if you have consecutive space characters, or glob characters. Use Method 1, or even better,

IFS=, read -r -d '' -a arr < <(printf '%s,\0' "$a")

which is the canonical way of splitting a string in Bash. See How do I split a string on a delimiter in Bash? .

Upvotes: 3

Related Questions