Bash和传递给argv的双引号 [英] Bash and Double-Quotes passing to argv

查看:436
本文介绍了Bash和传递给argv的双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经重新利用这个例子来保持它的简单,但我试图做的就是一个嵌套的双引号的字符串作为一个单一的argv值当的bash shell执行它。

I have re-purposed this example to keep it simple, but what I am trying to do is get a nested double-quote string as a single argv value when the bash shell executes it.

下面是脚本示例:

set -x
command1="key1=value1 \"key2=value2 key3=value3\""
command2="keyA=valueA keyB=valueB keyC=valueC"
echo $command1
echo $command2

的输出是:

++ command1='key1=value1 "key2=value2 key3=value3"'
++ command2='keyA=valueA keyB=valueB keyC=valueC'
++ echo key1=value1 '"key2=value2' 'key3=value3"'
key1=value1 "key2=value2 key3=value3"
++ echo keyA=valueA keyB=valueB keyC=valueC
keyA=valueA keyB=valueB keyC=valueC

我做的测试,以及,那当你在命令行上的一切,嵌套的报价信息被设置为一个单一的argv的值。即。

I did test as well, that when you do everything on the command line, the nested quote message IS set as a single argv value. i.e.

prog.exe argument1 "argument2 argument3"

argv[0] = prog.exe
argv[1] = argument1
argv[2] = argument2 argument3


使用上面的例子:


Using the above example:

command1="key1=value1 \"key2=value2 key3=value3\""

该错误,我的argv正在添加是一样回来:

The error is, my argv is comming back like:

arg[1] = echo 
arg[2] = key1=value1 
arg[3] = "key2=value2
arg[4] = key3=value3"

在这里我真的希望我的argv [3]值为键2 =值KEY3 =值3

where I really want my argv[3] value to be "key2=value2 key3=value3"

我注意到,调试(设置-x)显示了在那里我的论点得到破点的单引号这还挺表示它正在考虑这些破发点的争论......只是不知道。

I noticed that debug (set -x) shows a single-quote at the points where my arguments get broken which kinda indicates that it is thinking about the arguments at these break point...just not sure.

任何想法真的会在这里?如何更改脚本?

Any idea what is really going on here? How can I change the script?

先谢谢了。

推荐答案

正在发生的事情是,你的嵌套引用是文字,而不是解析成由外壳单独的参数。 庆典来处理这种使用的最佳方法是使用数组而不是字符串:

What is happening is that your nested quotes are literal and not parsed into separate arguments by the shell. The best way to handle this using bash is to use an array instead of a string:

args=('key1=value1', 'key2=value2 key3=value3')
prog.exe "${args[@]}"

借助猛砸FAQ50 有一些更多的范例和使用实例动态命令。

The Bash FAQ50 has some more examples and use cases for dynamic commands.

这篇关于Bash和传递给argv的双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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