Search code examples
bashshellquoting

echo removes leading whitespace in a Bash variable


Newbie to bash here. I'm hoping to prepend a single whitespace to a variable in bash, currently I have the following, which doesn't seem to work:

space=`printf '%1s' ' '`
mystr='hello'

mystr="$space$mystr"
echo $mystr

So instead of printing out "hello", I would like the result to be " hello", which has an additional whitespace at the beginning. What's the correct way to do this? Thanks.


Solution

  • The leading space is being removed by shell because of word splitting. Enclose your variable in double quotes to disable word splitting:

    echo "$mystr"
    

    See this post: I just assigned a variable, but echo $variable shows something else

    See these docs as well: Word Splitting and Field Splitting