echo removes leading whitespace in a Bash variable [duplicate]

大兔子大兔子 提交于 2020-03-24 03:24:29

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/45088223/echo-removes-leading-whitespace-in-a-bash-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!