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)
这是要理解的第一部分;第二种情况很简单,我想不需要解释。
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)
在这个命令中:
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'
被整体解释为一个参数;作为“命令字符串”。