首页 > 解决方案 > 如何在bash数组元素中转义引号

问题描述

我想像这样创建一个数组

array=(

"element1 with "quoted string""
"element2 without double quoted string"
"element3"
)

运行代码后输出

echo ${array[0]}                                                               
element1 with quoted.

我正在尝试在 echo 输出中包含引号。我该怎么做呢?

标签: arraysbashescapingquotes

解决方案


要么使用单引号,

array=(
'element1 with "quoted string"'
...
)

或转义文字双引号:

array=(
"element1 with \"quoted string\""
...
)

您的第一个嵌套引号关闭了开头引号,但quoted仍被视为当前单词的一部分。数组的下一个元素在string其末尾附加了一个空字符串。


推荐阅读