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

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

问题描述

我重新设计了这个例子以保持简单,但我想要做的是在 bash shell 执行它时将嵌套的双引号字符串作为单个 argv 值.

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] 值为key2=value2 key3=value3"

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

我注意到 debug (set -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?

提前致谢.

推荐答案

发生的情况是您的嵌套引号是字面量,而没有被 shell 解析为单独的参数.使用 bash 处理此问题的最佳方法是使用数组而不是字符串:

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[@]}"

Bash FAQ50 提供了更多动态命令的示例和用例.

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

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

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