Tuesday, November 27, 2012

Assigning a string to shell variable with successive spaces

My friend Sumeeth called me saying that he is trying to assign a string with successive spaces to a shell variable, but the spaces are getting removed.

Linux environment, using bash shell

export test="Hello   World"

echo $test

Hello World <----------extra spaces in middle are removed.  This is because of IFS.  By default it will be set to <space><tab><newline>

So one way of doing this is to change IFS, do the assignment and put the IFS back.

export old_IFS=$IFS
export IFS="\n\t"
export test="Hello   World"
echo $test
Hello   World  <------spaces are retained

No comments:

Post a Comment