1

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
fittaoee
  • 147
  • 1
  • 5
  • 14

1 Answers1

12

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

codeforester
  • 39,467
  • 16
  • 112
  • 140