在bash参数preserve行情 [英] Preserve Quotes in bash arguments

查看:104
本文介绍了在bash参数preserve行情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个bash脚本,将打印和复杂的参数传递到另一个外部程序。

I am making a bash script that will print and pass complex arguments to another external program.

./script -m root@hostname,root@hostname -o -q -- 'uptime ; uname -a'

我如何打印的原始参数这样:

How do I print the raw arguments as such:

-m root@hostname,root@hostname -o -q -- 'uptime ; uname -a'

使用 $ @ $ * 删除周围单引号的正常运行时间; -a的uname 这可能导致意外的结果。我的脚本不需要解析每个参数。我只需要打印/日志参数字符串,并将其传递给他们究竟是如何给另一个程序。

Using $@ and $* removes the single quotes around uptime ; uname -a which could cause undesired results. My script does not need to parse each argument. I just need to print / log the argument string and pass them to another program exactly how they are given.

我知道我可以逃避的东西,如'正常运行时间; -a的uname'引号,但我不能保证用户将这样做。

I know I can escape the quotes with something like "'uptime ; uname -a'" but I cannot guarantee the user will do that.

推荐答案

的参数传递给您的脚本之前,所以这已经太晚了preserve他们的报价都被删除。路过时到内部命令的参数,并重建等效引述你可以做的是preserve它们的效果/逃脱的论据版印刷。

The quotes are removed before the arguments are passed to your script, so it's too late to preserve them. What you can do is preserve their effect when passing the arguments to the inner command, and reconstruct an equivalent quoted/escaped version of the arguments for printing.

有关传递参数的内部命令$ @ - 用双引号,$ @ preserves原来的断字,这意味着内部命令收到完全相同的参数列表,你的脚本一样。

For passing the arguments to the inner command "$@" -- with the double-quotes, $@ preserves the original word breaks, meaning that the inner command receives exactly the same argument list that your script did.

有关打印,您可以使用%Q格式在bash的printf命令重建引用。请注意,这并不总是重建原始报价,但会构建一个的相当于的报价/转义字符串。例如,如果你传递的参数'的正常运行时间; -a的uname 它可能会打印的正常运行时间\\ \\; \\的uname \\ -a 正常运行时间; -a的uname 或任何其他等效(见@William Pursell对类似的例子回答)。

For printing, you can use the %q format in bash's printf command to reconstruct the quoting. Note that this won't always reconstruct the original quoting, but will construct an equivalent quoted/escaped string. For example, if you passed the argument 'uptime ; uname -a' it might print uptime\ \;\ uname\ -a or "uptime ; uname -a" or any other equivalent (see @William Pursell's answer for similar examples).

下面是一个使用这些的例子:

Here's an example of using these:

printf "Running command:"
printf " %q" innercmd "$@" # note the space before %q -- this inserts spaces between arguments
printf "\n"
innercmd "$@"

这篇关于在bash参数preserve行情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆