Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to split a string into two variables

Tags:

bash

shell

ifs

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)?

like image 847
coda Avatar asked Nov 22 '13 12:11

coda


1 Answers

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=
like image 89
fedorqui 'SO stop harming' Avatar answered Sep 18 '22 04:09

fedorqui 'SO stop harming'