与 printf 命令混淆?

Nar*_*wen 13 command-line bash

我必须在一个打印命令中打印以下三行而不使用 echo 命令。所以我选择了 printf 命令。这里是三行:

  Different characters can be represented and supported 
  in the print command, for example: 
  x-y, X+Y, –, +, <, >, %, $, #, &.
Run Code Online (Sandbox Code Playgroud)

到目前为止我所做的是:

   printf "
   Different characters can be represented and supported 
   in the print command, for example: 
   x-y, X+Y, –, +, <, >, %, $, #, &.
   "
Run Code Online (Sandbox Code Playgroud)

但是我在第三行 ',' 中遇到了 bash 错误。

所以有人会启发我。

Oli*_*Oli 15

%中的特殊字符printf。这就是导致错误的原因。你需要将它转义为%%.

$也可以在双引号内被外壳替换,因此您应该转义 ( \$)。通常使用单引号更容易。

  • 美元符号只有在后面跟有一个有效的变量名时才比较特殊,这里不是这种情况。 (5认同)

Rad*_*anu 13

更好地使用:

printf "Different characters can be represented and supported\n\
in the print command, for example:\n\
x-y, X+Y, –, +, <, >, %%, $, #, &.\n"
Run Code Online (Sandbox Code Playgroud)

正如其他人在这里所说的那样,您会遇到该错误,因为%字符是特殊的并且必须转义。

查看man 1 printf更多信息。

  • `printf` 的重点在于 `%` 字符以及它的作用! (4认同)

gle*_*man 10

%是 printf 的特殊之处:它是格式说明符中的前导字符。如果您想要文字百分比,请使用%%


tho*_*hom 10

看到当您不允许使用该echo命令时,您选择使用该命令,这有点令人惊讶printf

为什么不cat呢?

#!/bin/bash

cat<<'EOF'
Different characters can be represented and supported
in the print command, for example:
x-y, X+Y, –, +, <, >, %, $, #, &.
EOF
Run Code Online (Sandbox Code Playgroud)

  • 为了避免在文本中解释像`$foo`这样的字符串,使用`cat &lt;&lt;'EOF'而不是`cat &lt;&lt;EOF`。 (2认同)