如何回显“$@”以便结果是有效的bash并保持正确的引用?

我该怎么放wrapper.sh,如果我想这样的:

wrapper.sh "hello world" arg2 '' "this ' thing"

输出:

Now please run:
other-command "hello world" arg2 '' "this ' thing"

我意识到原始引用丢失并且输出可能会以不同的方式引用并且很好,只要other-command在命令被剪切'n'粘贴到外壳时获得正确的参数。

我知道"$@"哪个适用于调用其他程序,但不适用于回显有效的 bash,STDOUT据我所知。

这看起来很不错,但需要 Perl String::ShellQuote(我想避免):

$ perl -MString::ShellQuote -E 'say shell_quote @ARGV' other-command "hello world" arg2 '' "this ' thing"
other-command 'hello world' arg2 '' 'this ''' thing'

这不起作用 - 请注意零长度 arg 是如何丢失的:

$ perl -E 'say join(" ", map { quotemeta $_ } @ARGV)' other-command "hello world" arg2 '' "this ' thing"
other-command hello world arg2  this ' thing

再次,我想避免使用 Perl 或 Python ...

回答

您可以使用@Q参数转换。

$ set -- "hello world" arg2 '' 'this " thing'
$ echo other-command "${@@Q}"
other-command 'hello world' 'arg2' '' 'this " thing'

  • This tends to look nicer than `printf %q`, which only uses backslashes, no quotes. For whatever reason they quote things differently.

回答

如果您打算重新调整输出eval,则需要printf "%q"。您的脚本可能如下所示:

echo Now please run:
echo "other-command$(printf " %q" "$@")"


以上是如何回显“$@”以便结果是有效的bash并保持正确的引用?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>