Trying to split a string into two variables

coda picture coda · Nov 22, 2013 · Viewed 14.9k times · Source

I'm trying to split a string into two variables (without having to use a while loop):

var="hello:world"
IFS=':' read var1 var2 <<< $var

echo "var1: $var1"
echo "var2: $var2"

but i'm not getting the desired result:

var1: 'hello world'
var2: ''

Could anybody please explain if it's possible to do it this way (or similar way)?

Answer

fedorqui &#39;SO stop harming&#39; picture fedorqui 'SO stop harming' · Nov 22, 2013

This is a bug in Bash 4.2. See chepner's answer for a proper explanation.


It is about quotes. Use:

IFS=':' read var1 var2 <<< "$var"
                           ^    ^

instead of

IFS=':' read var1 var2 <<< $var

See result:

$ IFS=':' read var1 var2 <<< "$var"
$ echo "var1=$var1, var2=$var2"
var1=hello, var2=world

But

$ IFS=':' read var1 var2 <<< $var
$ echo "var1=$var1, var2=$var2"
var1=hello world, var2=