在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:06:35  来源:igfitidea点击:

Printing asterisk ("*") in bash shell

bashshell

提问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:

结果:

enter image description here

在此处输入图片说明

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:

你有两个问题:

  1. Useless Use of Echo in Backticks

  2. Always quote what you echo

  1. 反引号中 Echo 的无用使用

  2. 总是引用你的话 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 cronSenis 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 $wordswould only loop once over the literal token foo bar baz.)

(这循环了 3 次。引用$words只会在文字标记上循环一次foo bar baz。)

Wildcard expansion:

通配符扩展:

pattern='file*.txt'
ls $pattern

(Quoting $patternwould 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, bashwill see *and perform filename expansion. *expands to all files in your current directory.

如果不使用双引号,bash将看到*并执行文件名扩展*扩展到当前目录中的所有文件。