将字符串转换为参数当bash不解析报价 [英] Bash doesn't parse quotes when converting a string to arguments

查看:120
本文介绍了将字符串转换为参数当bash不解析报价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题。在bash 3:

This is my problem. In bash 3:

$ test='One "This is two" Three'
$ set -- $test
$ echo $2
"This

如何获得的bash了解行情,并返回$ 2​​作为这两个,而不是?不幸的是我不能改变一个名为测试在这个例子中,变量的建设。

How to get bash to understand the quotes and return $2 as This is two and not "This? Unfortunately I cannot alter the construction of the variable called test in this example.

推荐答案

之所以出现这种情况是因为在该壳解析命令行命令:它解析(和删除)的报价和逃逸,然后替换变量值。由时间 $测试获取与一这两个三,为时已晚的报价以更换他们的预期效果。

The reason this happens is because of the order in which the shell parses the command line: it parses (and removes) quotes and escapes, then replaces variable values. By the time $test gets replaced with One "This is two" Three, it's too late for the quotes to have their intended effect.

简单(但危险)的方式来做到这一点是通过添加解析的另一层面评估

The simple (but dangerous) way to do this is by adding another level of parsing with eval:

$ test='One "This is two" Three'
$ eval "set -- $test"
$ echo "$2"
This is two

(请注意,在回声命令引号是没有必要的,但是是一个很好的通用做法。)

(Note that the quotes in the echo command are not necessary, but are a good general practice.)

我说这是危险的原因是,它不只是回去重新分析了引号的字符串,它可以追溯到并重新解析一切的,也许包括事情你不想间preTED像命令替换。假设你已经建立

The reason I say this is dangerous is that it doesn't just go back and reparse for quoted strings, it goes back and reparses everything, maybe including things you didn't want interpreted like command substitutions. Suppose you had set

$ test='One `rm /some/important/file` Three'

... 评估将实际运行 RM 命令。所以,如果你不能在 $测试是安全,不要使用此结构

...eval will actually run the rm command. So if you can't count on the contents of $test to be "safe", do not use this construct.

顺便说一句,做这种事情的正确方法是用一个数组:

BTW, the right way to do this sort of thing is with an array:

$ test=(One "This is two" Three)
$ set -- "${test[@]}"
$ echo "$2"
This is two

不幸的是,这需要的是如何创建的变量控制。

Unfortunately, this requires control of how the variable is created.

这篇关于将字符串转换为参数当bash不解析报价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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