在 bash shell 中打印星号(“*”)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25277037/
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
Printing asterisk ("*") in bash shell
提问by user2499325
a=5
echo "*/$aMin * * * * bash /etc/init.d/ckDskCheck.sh"
When I try to run the following code, it displays properly
当我尝试运行以下代码时,它显示正确
*/5 * * * * bash /etc/init.d/ckDskCheck.sh
But when I try to assign the result using the following code to the variable and print it out, it displays as this:
但是当我尝试使用以下代码将结果分配给变量并将其打印出来时,它显示为:
a=5
cronSen=`echo "*/$a * * * * bash /etc/init.d/ckDskCheck.sh"`
echo $cronSen
Result:
结果:
So I try to escape the asterisk by
所以我试图逃避星号
cronSen=`echo "\*/$a \* \* \* \* bash /etc/init.d/ckDskCheck.sh"`
But it still doesn't work. Why? How can I fix this?
但它仍然不起作用。为什么?我怎样才能解决这个问题?
回答by tripleee
You have two problems:
你有两个问题:
Useless Use of Echo in Backticks
Always quote what you
echo
反引号中 Echo 的无用使用
总是引用你的话
echo
So the fixed code is
所以固定代码是
a=5
cronSen="*/$a * * * * bash /etc/init.d/ckDskCheck.sh"
echo "$cronSen"
It appears you may also have a Useless Use of Variable, but perhaps cronSen
is useful in a larger context.
看起来您可能也有一个 Useless Use of Variable,但可能cronSen
在更大的上下文中很有用。
In short, quote everything where you do not require the shell to perform token splitting and wildcard expansion.
简而言之,引用不需要 shell 执行标记拆分和通配符扩展的所有内容。
Token splitting;
代币分裂;
words="foo bar baz"
for word in $words; do
:
(This loops three times. Quoting $words
would only loop once over the literal token foo bar baz
.)
(这循环了 3 次。引用$words
只会在文字标记上循环一次foo bar baz
。)
Wildcard expansion:
通配符扩展:
pattern='file*.txt'
ls $pattern
(Quoting $pattern
would attempt to list a single file whose name is literally file*.txt
.)
(引用$pattern
将尝试列出名称为字面意思的单个文件file*.txt
。)
In more concrete terms, anything containing a filename should usually be quoted.
更具体地说,通常应该引用任何包含文件名的内容。
A variable containing a list of tokens to loop over or a wildcard to expand is less frequently seen, so we sometimes abbreviate to "quote everything unless you know precisely what you are doing".
包含要循环的标记列表或要扩展的通配符的变量不太常见,因此我们有时缩写为“引用所有内容,除非您确切地知道自己在做什么”。
回答by cuonglm
You must use double quote when echo your variable:
回显变量时必须使用双引号:
echo "$cronSen"
If you don't use double quote, bash
will see *
and perform filename expansion. *
expands to all files in your current directory.
如果不使用双引号,bash
将看到*
并执行文件名扩展。*
扩展到当前目录中的所有文件。