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



如果我想要这个,我在wrapper.sh中放什么:

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

输出:

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

我意识到并很满意原始报价会丢失,输出可能会以不同的方式报价,只要other-command在命令被剪切"粘贴"到shell时获得正确的参数。

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

这看起来很不错,但需要PerlString::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'

如果您想要重新计算输出eval,那么您需要printf "%q"。你的脚本可能看起来像:

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

最新更新