Bash:需要去除字符串周围的单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27793125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:07:48  来源:igfitidea点击:

Bash: need to strip single quotes around a string

bash

提问by Maddy

Following is the code snippet from my bash script:

以下是我的 bash 脚本中的代码片段:

....
....
for ((i=0; i<${#abc[@]}; i++))
  do
    xyz=${abc[i]}
....
....

When the value of 'xyz' is substituted in the script, the value has single quotes around it:

当在脚本中替换 'xyz' 的值时,该值周围有单引号:

'"6b76cdae-a4a8-4e88-989d-1581ae2d5b98"'

Why are the single quotes added and how do I strip them?

为什么要添加单引号以及如何去除它们?

Thanks!

谢谢!

采纳答案by nino_mezza

You can replace

你可以更换

xyz=${abc[i]}

xyz=${abc[i]}

with

eval xyz=${abc[i]}

评估 xyz=${abc[i]}

And here is an illustrating example what happens:

这是一个说明会发生什么的示例:

$ foo="'"'"bar"'"'"
$ echo $foo
'"bar"'
$ eval foo=$foo
$ echo $foo
"bar"
$ eval foo=$foo
$ echo $foo
bar

So, what happens with the holy evalis that the assignment gets split into two parts:

所以,神圣的事情eval是分配被分成两部分:

  1. Evaluate $abc
  2. Assign to $xyz
  1. 评估 $abc
  2. 分配给 $xyz

instead of just Step 2.

而不仅仅是第 2 步。

Maybe in your case you should consider to already change the assignment of abcbut i don't know because of ignorance ;)

也许在您的情况下,您应该考虑已经更改分配,abc但由于无知,我不知道;)

回答by Cyrus

You can try to remove allsingle quotes in array abc with Parameter Expansion:

您可以尝试使用参数扩展删除数组 abc中的所有单引号:

abc=(${abc[@]//\'/})

You can try to remove allsingle quotes in string xyz with Parameter Expansion:

您可以尝试使用参数扩展删除字符串 xyz中的所有单引号:

xyz=${xyz//\'/}