bash 将数组分配给变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12303974/
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-09 22:38:20  来源:igfitidea点击:

Assign array to variable

bash

提问by user1638962

The issue about assigning arrays to variables in bash script seems rather complicated:

在 bash 脚本中将数组分配给变量的问题似乎相当复杂:

a=("a" "b" "c")
b=$a

echo ${a[0]} 
echo ${a[1]}

echo ${b[0]} 
echo ${b[1]} 

leads to

造成

a 
b 
a

instead of

代替

a
b
a
b

Why? How can I fix it?

为什么?我该如何解决?

回答by kojiro

If you want to reassigna variable that holds an array to another name, you do it like this:

如果要将保存数组的变量重新分配给另一个名称,请执行以下操作:

a=('a' 'b' 'c')
b=( "${a[@]}" )

回答by Chad Skeeters

Why?

为什么?

If ais an array, $aexpands to the first element in the array. That is why bin your example only has one value. In bash, variables that refer to arrays aren't assignable like pointers would be in C++ or Java. Instead variables expand(as in Parameter Expansion) into strings and those strings are copied and associated with the variable being assigned.

如果a是数组,则$a扩展到数组中的第一个元素。这就是为什么b在您的示例中只有一个值。在 bash 中,引用数组的变量不可分配,就像 C++ 或 Java 中的指针一样。相反,变量扩展(如在参数扩展中)为字符串,这些字符串被复制并与被分配的变量相关联。

How can I fix it?

我该如何解决?

To copy a sparse array that contains values with spaces, the array must be copied one element at a time by the indices - which can be obtained with ${!a[@]}.

要复制包含带有空格的值的稀疏数组,必须通过索引一次复制一个元素——这可以通过 ${!a[@]} 获得。

declare -a b=()
for i in ${!a[@]}; do
    b[$i]="${a[$i]}"
done

From the bash man page:

从 bash 手册页:

It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and ${!name[*]} expand to the indices assigned in array variable name. The treatment when in double quotes is similar to the expansion of the special parameters @ and * within double quotes.

可以获得数组的键(索引)和值。${!name[@]} 和 ${!name[*]} 扩展为数组变量 name 中分配的索引。双引号中的处理类似于双引号中特殊参数@ 和* 的扩展。

Here's a script you can test on your own:

这是一个您可以自己测试的脚本:

#!/bin/bash

declare -a a=();
a[1]='red hat'
a[3]='fedora core'

declare -a b=();

# Copy method that works for sparse arrays with spaces in the values.
for i in ${!a[@]}; do
    b[$i]="${a[$i]}"
done

# does not work, but as LeVar Burton says ...
#b=("${a[@]}")

echo a indicies: ${!a[@]}
echo b indicies: ${!b[@]}

echo "values in b:"
for u in "${b[@]}"; do
    echo $u
done

Prints:

印刷:

a indicies: 1 3
b indicies: 1 3  # or 0 1 with line uncommented
values in b:
red hat
fedora core

This also works for associative arrays in bash 4, if you use declare -A(with capital A instead of lower case) when declaring the arrays.

如果declare -A在声明数组时使用(大写 A 而不是小写),这也适用于 bash 4 中的关联数组。