如何用引号引起来的多单词字符串替换为参数? [英] How to substitute quoted, multi-word strings as arguments?

查看:84
本文介绍了如何用引号引起来的多单词字符串替换为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将包含多个带引号的单词的字符串变量替换为命令的参数.

因此,给出以下示例脚本(请注意,shebang中的-x会导致将输出记录到stderr),

#!/bin/bash -x

myArg="\"hello\" \"world\""
echo "string is:" $myArg

exit

哪个给了我们

+ myArg='"hello" "world"'
+ echo 'string is:' '"hello"' '"world"'
string is: "hello" "world"
+ exit


第二行显示了实际传递给命令的内容; bash已为字符串中的每个单词添加了单引号.因此,如果我改为引用"$ myArg",则会发生相同的情况,但整个字符串而不是每个单词都会出现.

现在,想象一下,我们将字符串而不是echo传递给程序,在该程序中某些参数需要用引号引起来,例如"*"(不能由外壳扩展)./p>

为澄清起见,我不希望在扩展过程中添加任何单引号.我该如何实现?

解决方案

不要使用引号,而使用数组(请参见

如果确实需要使用字符串中带引号的字符串的形式,则您将不得不使用eval "echo $myArg"之类的东西(如果不小心,可能会导致一些非常讨厌的错误),或者自己解析(这将很困难).

I'm trying to substitute a string variable, containing multiple quoted words, as a parameter to a command.

Thus, given the following example script (Note the -x in the shebang, which causes the output to be logged to stderr),

#!/bin/bash -x

myArg="\"hello\" \"world\""
echo "string is:" $myArg

exit

Which gives us,

+ myArg='"hello" "world"'
+ echo 'string is:' '"hello"' '"world"'
string is: "hello" "world"
+ exit


Line two shows what is actually passed to the command; bash has added single quotes to each word in the string. If I instead, thusly, quote "$myArg", the same occurs but for the whole string rather than each word.

Now, imagine that instead of echo, we are passing the string to a program where some of the arguments need to be quoted patterns, such as "*" (which mustn't be expanded by the shell).

To clarify, I don't want the single quotes added at all during the expansion. How might I achieve this?

解决方案

Don't use quotes, use an array (see BashFAQ #050):

$ myArgs=("hello" "world" "multiword arg with * ?")
+ myArgs=("hello" "world" "multiword arg with * ?")
$ echo "${myArgs[@]}"
+ echo hello world 'multiword arg with * ?'
hello world multiword arg with * ?

If it really needs to be in the form of quoted strings within a string, you're either going to have to use something like eval "echo $myArg" (which can cause some really nasty bugs, if you aren't careful) or parse it yourself (which is going to be difficult).

这篇关于如何用引号引起来的多单词字符串替换为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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