为什么称为 /bin/sh -c echo foo 的 echo 不输出任何内容?

Sil*_*Fox 16 command-line shell echo arguments

例如,虽然这有效:

$回声富
富

这不会:

$ /bin/sh -c echo foo

而这样做:

$ /bin/sh -c 'echo foo; 回声栏'
富
酒吧

有解释吗?

Ija*_*han 21

man sh

-c string   If the -c option is present, then commands are read from string. 
            If there are arguments after the string, they are assigned to the
            positional parameters, starting with $0
Run Code Online (Sandbox Code Playgroud)

这意味着你的命令应该是这样的:

 $ sh -c 'echo "$0"' foo 
 foo
Run Code Online (Sandbox Code Playgroud)

相似地:

$ sh -c 'echo "$0 $1"' foo bar
foo bar
Run Code Online (Sandbox Code Playgroud)

这是要理解的第一部分;第二种情况很简单,我想不需要解释。

  • 恕我直言,解释很好,但考虑到提问者已经知道`/bin/sh -c 'echo foo; echo bar'` 有效,您可以简单地回答引用命令 `/bin/sh -c 'echo foo'` (3认同)
  • 更严格的标准一致性方法是`sh -c 'echo $1' echo foo` (2认同)

Mar*_*rco 18

$ echo foo
foo
Run Code Online (Sandbox Code Playgroud)

这个调用echo带有参数foo并且foo被打印出来。

$ /bin/sh -c echo foo
Run Code Online (Sandbox Code Playgroud)

这将使用参数调用 shellecho并提供foo作为参数 $0。在echo输出新行,你放弃FOO。如果要输出foo,请引用参数:

sh -c 'echo foo'
Run Code Online (Sandbox Code Playgroud)

或使用提供的参数:

sh -c 'echo $0' foo
Run Code Online (Sandbox Code Playgroud)

在这个例子中

$ /bin/sh -c 'echo foo; echo bar'
foo
bar
Run Code Online (Sandbox Code Playgroud)

使用echo foo; echo bar输出的参数调用 shell

foo
bar
Run Code Online (Sandbox Code Playgroud)


cha*_*aos 8

在这个命令中:

echo foo
Run Code Online (Sandbox Code Playgroud)

echo是二进制(或内置命令)并且foo是第一个参数。

这里:

/bin/sh -c echo foo
Run Code Online (Sandbox Code Playgroud)

/bin/sh是二进制文件,它的第一个参数是-c,它本身接受一个“命令字符串”作为参数。这是echo在上面的例子中。然后是第三个参数:foo它是 的参数/bin/sh,而不是echo。这就是为什么在你的第三个例子中:

/bin/sh -c 'echo foo; echo bar'
Run Code Online (Sandbox Code Playgroud)

...两者都打印出来。你引用了这个论点。因此:第一个参数是-c,并且这个参数的参数是'echo foo; echo bar'被整体解释为一个参数;作为“命令字符串”。