子 shell 执行带有参数的命令的奇怪行为

Tom*_*ino 0 bash subshell

当我直接执行以下命令时:

root@busybox-694d76bb5d-2gcvh:/# mysql -hmariadb -P3306 -uroot -ppassword -e 'SELECT 1'
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

mysql: [Warning] Using a password on the command line interface can be insecure.
+---+
| 1 |
+---+
| 1 |
+---+
Run Code Online (Sandbox Code Playgroud)

但是,在子 shell 中使用相同的命令,如下所示:

$(mysql -hmariadb -P3306 -uroot -ppassword -e 'SELECT 1')
Run Code Online (Sandbox Code Playgroud)

输出:

mysql: [Warning] Using a password on the command line interface can be insecure.
bash: 1: command not found
Run Code Online (Sandbox Code Playgroud)

为什么 bash 将我作为参数发送的“1”解释为在子 shell 中发送时就好像它是一个单独的命令一样?

Aar*_*ron 5

这不是1bash 解释的参数的一部分,而是命令的输出。

首先,您需要知道mysql有两种默认的输出模式:tableraw。当命令的输出流是终端并打印人类可读的输出时,使用第一个。第二个用于其他用途,并打印可由脚本轻松操作的输出。您可以使用我已链接其文档的选项强制执行其中之一。

其次,您需要了解 simple(subshell)$(command substitution): 在这两种情况下,命令都在子 shell 中运行,但通过命令替换,命令的输出将替换在原始命令行中,然后执行。

因此,当您编写时发生的情况$(mysql command)是,它的输出是1(原始结果)而不是您之前看到的表,然后该表无法解析为命令。

(echo 1)通过测试 和之间的差异,您可以更轻松地看到 subshel​​l 和命令替换之间的差异$(echo 1),其中第二个将以与当前命令完全相同的方式失败。