将字符串中指定的元素附加到bash数组的引号中 [英] Appending elements specified in a string with quotes to a bash array
问题描述
我正在尝试将一个项目追加到存储在变量中的数组中,但是它并没有完全按照我的期望进行操作.
I am trying to append an item to an array that is stored in a variable, however it's not acting entirely how I'd expect it to.
这就是我想要做的:
array=()
item_to_add="1 '2 3'"
array+=(${item_to_add})
for item in "${array[@]}"; do
echo "item: ${item}"
done
我希望它能输出以下内容:
I'd expect this to output the following:
item: 1
item: '2 3'
但是我却得到以下输出:
However I get the following output instead:
item: 1
item: '2
item: 3'
有什么办法可以使它像这样的代码而无需使用 eval
之类的东西?
Is there any way to make it act like this code without using something like eval
?
array=()
array+=(1 '2 3')
for item in "${array[@]}"; do
echo "item: ${item}"
done
及其输出:
item: 1
item: '2 3'
推荐答案
xargs
解析其输入中的引号.这通常是一个(规范级别的)错误,而不是一个功能(它使具有文本引号的文件名在没有非POSIX扩展名(例如 -d
或 -0 代码>覆盖行为),但在当前情况下非常方便:
xargs
parses quotes in its input. This is usually a (specification-level) bug rather than a feature (it makes filenames with literal quotations nearly impossible to work with without non-POSIX extensions such as -d
or -0
overriding the behavior), but in present circumstances it comes in quite handy:
array=()
item_to_add="1 '2 3'"
while IFS= read -r -d '' item; do # read NUL-delimited stream
array+=( "$item" ) # and add each piece to an array
done < <(xargs printf '%s\0' <<<"$item_to_add") # transform string to NUL-delimited stream
printf 'item: %s\n' "${array[@]}"
...发出...
item: 1
item: 2 3
这篇关于将字符串中指定的元素附加到bash数组的引号中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!