bash 输出shell变量时如何保留空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22378755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to preserve spaces when outputting a shell variable?
提问by gluuke
For string matching purposes I need to define a bash variable with leading spaces. I need to define this starting from an integer, like:
出于字符串匹配的目的,我需要定义一个带有前导空格的 bash 变量。我需要从一个整数开始定义它,例如:
jj=5
printf seems to me a good idea, so if I want to fill spaces up to 6 character:
printf 在我看来是个好主意,所以如果我想填充最多 6 个字符的空格:
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.
前导空格被删除,我只得到$jj
原来的整数。
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?)
(这相当于:v=' val'; echo $v$v
。为什么输出中没有前导和多个空格?)
回答by l0b0
Use More Quotes!echo "$jpat"
will do what you want.
使用更多报价!echo "$jpat"
会做你想做的。
There is another issue with what you're doing: Command substitutions will removetrailing 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.
您正在做的事情还有另一个问题:命令替换将删除尾随的换行符。这在printf
您使用的命令中不是问题,但例如分配jpat=$(printf " %6i\n" "$jj")
会给您与您的命令完全相同的结果。