anusngh anusngh - 4 months ago 16
Linux Question

How to use comma(,) as a value for a variable in bash

I want to use comma as value for a variable in bash ;

Code:

a=xyz
y=pqr
seprator=','
string=$a$seprator$y
echo $string

Output is:
xyz pqr

Expected output:
xyz,pqr


Please help,Thanks

Answer

You must have IFS set to comma. See this example:

IFS=,
echo $string
xyz pqr

unset IFS
echo $string
xyz,pqr

However it is highly recommended to quote your variable like

echo "$string"

Even this IFS=, will work with quoted variable:

IFS=,
echo "$string"
xyz,pqr