简体   繁体   English

Bash 复制包含数组作为参考的变量

[英]Bash copy variable containing array as reference

With the following code I can copy an array content to another one so that when altering one array the other is untouched.使用以下代码,我可以将数组内容复制到另一个数组,以便在更改一个数组时另一个数组保持不变。

#!/bin/bash
declare -a ARRAY_A=(a b c d e)
ARRAY_B=("${ARRAY_A[@]}")

echo "Before removal:"

printf "%s " ${ARRAY_A[@]}
echo
printf "%s " ${ARRAY_B[@]}
echo

echo
echo "After removal:"
unset ARRAY_A[0]

printf "%s " ${ARRAY_A[@]}
echo
printf "%s " ${ARRAY_B[@]}
echo

Prints:印刷:

Before removal:
a b c d e 
a b c d e 

After removal:
b c d e 
a b c d e

Is it possible to copy the reference to that array instead, so that when altering one array the "other" (which is the same then) appears to be changed as well (like below)?是否可以改为复制对该数组的引用,以便在更改一个数组时,“另一个”(当时相同)似乎也发生了变化(如下所示)?

Before removal:
a b c d e 
a b c d e 

After removal:
b c d e 
b c d e

Yes?是的? Just use a bash name reference.只需使用 bash 名称参考即可。

#!/bin/bash
declare -a ARRAY_A=(a b c d e)
declare -n ARRAY_B=ARRAY_A

echo "Before removal:"

printf "%s " "${ARRAY_A[@]}"
echo
printf "%s " "${ARRAY_B[@]}"
echo

echo
echo "After removal:"
unset ARRAY_A[0]

printf "%s " "${ARRAY_A[@]}"
echo
printf "%s " "${ARRAY_B[@]}"
echo

Note: prefer to use lowercase variables in your scripts.注意:更喜欢在脚本中使用小写变量。 Upper case variables are by convention meant to be exported variables, like COLUMN, LINES, PWD, UID, IFS, etc.大写变量按照惯例意味着导出变量,如 COLUMN、LINES、PWD、UID、IFS 等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM