复制bash数组且仅存在第一个元素的问题 [英] Issue with copying bash array and only first element being present

查看:55
本文介绍了复制bash数组且仅存在第一个元素的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个数组,在存储旧值的同时临时更改其值,执行一些计算,然后再恢复原始数组的值.在此过程中,我原来的数组声明,重新分配数组,甚至临时数组副本似乎都可以正常工作.但是,我在将数组最终恢复到其原始值时遇到了一个问题.

I would like to declare an array, temporally change it's value while storing the old value, perform some computation and then later restore the original array value. Of this process, my original array declaration, reassigning the array, and even the temporary array copy seem to all be working. However I am running into an issue with the final restoration of the array back to its original value.

以下脚本演示了该问题. MY_ARR 是主阵列,而 SAVE_MY_ARR 是我正在制作的副本,而在恢复之前我临时修改了该数组.根据脚本注释,所有内容均按预期输出,但原始数组在恢复其值后除外.我在这里做错了什么?

The below script demonstrates the issue. MY_ARR is the main array and SAVE_MY_ARR is the copy I am making while I modify the array temporarily before restoring it. As per the script comments, everything prints out as expected, with the exception of the original array after restoring its value. What am I doing incorrectly here?

脚本:

IFS=$'\n'

MY_ARR=(one two three)
# GOOD: prints "one,two,three,"
for i in ${MY_ARR[@]}; do
    echo -n "$i,"
done
echo ""

SAVE_MY_ARR=("${MY_ARR[@]}")
MY_ARR=(foo)
# GOOD: prints "foo,"
for i in ${MY_ARR[@]}; do
    echo -n "$i,"
done
echo ""

# GOOD: prints "one;two;three"
for i in ${SAVE_MY_ARR[@]}; do
    echo -n "$i;"
done
echo ""

# BAD: prints "one," and not "one,two,three,"
MY_ARR=("${SAVE_MY_ARR}")
for i in ${MY_ARR[@]}; do
    echo -n "$i,"
done
echo ""

输出:

one,two,three,
foo,
one;two;three;
one,

推荐答案

我认为这是一个错字错误,请替换为:

I think it's a typo mistake, here replace:

# BAD: prints "one," and not "one,two,three,"
MY_ARR=("${SAVE_MY_ARR}")

通过

# BAD: prints "one," and not "one,two,three,"
MY_ARR=("${SAVE_MY_ARR[@]}")

将[@]添加到SAVE_MY_ARR.

Adding the [@] to SAVE_MY_ARR.

这篇关于复制bash数组且仅存在第一个元素的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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