How to preserve spaces when outputting a shell variable? [duplicate]

不问归期 提交于 2019-12-29 01:59:08

问题


For string matching purposes I need to define a bash variable with leading spaces. I need to define this starting from an integer, like:

jj=5

printf seems to me a good idea, so if I want to fill spaces up to 6 character:

jpat=`printf "  %6i"  $jj`

but unluckly when I am trying to recall the variable:

echo $jpat

the leading whitespaces are removed and I only get the $jj integer as it was.

Any solution to keep such spaces?

(This is equivalent to this: v=' val'; echo $v$v. Why aren't there leading and multiple spaces in output?)


回答1:


Use More Quotes! echo "$jpat" will do what you want.

There is another issue with what you're doing: Command substitutions will remove trailing newlines. It's not an issue in the printf command you're using, but for example assigning jpat=$(printf " %6i\n" "$jj") would give you exactly the same result as your command.



来源:https://stackoverflow.com/questions/22378755/how-to-preserve-spaces-when-outputting-a-shell-variable

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