Bash: 如何正确引用命令的结果
Bash: How do I properly quote the results of a command
我的问题归结为:
echo $(echo '*')
即输出当前目录下所有文件的名称。
我不要那个。我想要一个文字星号 (*
).
如何以通用方式执行此操作?
我上面的例子被简化了。星号不是字面上写在我的 bash 脚本中 - 它来自另一个命令的结果。
所以这可能更接近我的真实情况:
echo $(my-special-command)
我只想得到my-special-command
的文字输出;我不想要扩展任何嵌入的星号(或其他特殊字符)。
如何以通用方式执行此操作?
我想我可以在 运行 命令之前执行 set -f
,但我如何确定涵盖所有内容?这会关闭路径名扩展,但是其他种类呢?我对 my-special-command
可能产生的输出的控制为零,因此必须能够正确处理所有内容。
只需用双引号将 Command substitution 括起来:
echo "$(my-special-command)"
它叫做 globbing,你有多种方法来防止它:
echo * # will expand to files / directories
echo "*" # Will print *
echo '*' # Will also print *
在你的例子中你可以简单的写:
echo "$(echo '*')"
您还可以通过使用 bash -f script.sh
或在您的代码中调用来关闭脚本中的 globbing:
#!/usr/bin/env bash
set -f
echo *
来自手册页的 "Command Substitution" 部分:
If the [command] substitution appears within double quotes, word splitting and
pathname expansion are not performed on the results.
通过引用命令扩展,可以防止其结果 *
进行路径名扩展。
$ echo "$(echo "*")"
我的问题归结为:
echo $(echo '*')
即输出当前目录下所有文件的名称。
我不要那个。我想要一个文字星号 (*
).
如何以通用方式执行此操作?
我上面的例子被简化了。星号不是字面上写在我的 bash 脚本中 - 它来自另一个命令的结果。
所以这可能更接近我的真实情况:
echo $(my-special-command)
我只想得到my-special-command
的文字输出;我不想要扩展任何嵌入的星号(或其他特殊字符)。
如何以通用方式执行此操作?
我想我可以在 运行 命令之前执行 set -f
,但我如何确定涵盖所有内容?这会关闭路径名扩展,但是其他种类呢?我对 my-special-command
可能产生的输出的控制为零,因此必须能够正确处理所有内容。
只需用双引号将 Command substitution 括起来:
echo "$(my-special-command)"
它叫做 globbing,你有多种方法来防止它:
echo * # will expand to files / directories
echo "*" # Will print *
echo '*' # Will also print *
在你的例子中你可以简单的写:
echo "$(echo '*')"
您还可以通过使用 bash -f script.sh
或在您的代码中调用来关闭脚本中的 globbing:
#!/usr/bin/env bash
set -f
echo *
来自手册页的 "Command Substitution" 部分:
If the [command] substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.
通过引用命令扩展,可以防止其结果 *
进行路径名扩展。
$ echo "$(echo "*")"