bash 如何在bash中将数组元素初始化为0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16486879/
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
How to initiate array element to 0 in bash?
提问by MOHAMED
declare -a MY_ARRAY=()
Does the declaration of array in this way in bash will initiate all the array elements to 0?
在bash中以这种方式声明数组是否会将所有数组元素初始化为0?
If not, How to initiate array element to 0?
如果不是,如何将数组元素初始化为 0?
回答by Sir Athos
Your example will declare/initialize an empty array.
您的示例将声明/初始化一个空数组。
If you want to initialize array members, you do something like this:
如果要初始化数组成员,请执行以下操作:
declare -a MY_ARRAY=(0 0 0 0) # this initializes an array with four members
If you want to initialize an array with 100 members, you can do this:
如果你想初始化一个有 100 个成员的数组,你可以这样做:
declare -a MY_ARRAY=( $(for i in {1..100}; do echo 0; done) )
Keep in mind that arrays in bash are not fixed length (nor do indices have to be consecutive). Therefore you can't initialize allmembers of the array unless you know what the number should be.
请记住,bash 中的数组不是固定长度的(索引也不必是连续的)。因此,除非您知道数字应该是多少,否则您无法初始化数组的所有成员。
回答by Todd A. Jacobs
Default Values with Associative Arrays
关联数组的默认值
Bash arrays are not fixed-length arrays, so you can't pre-initialize all elements. Indexed arrays are also not sparse, so you can't really use default values the way you're thinking.
Bash 数组不是固定长度的数组,因此您不能预先初始化所有元素。索引数组也不是稀疏的,因此您不能真正按照您的想法使用默认值。
However, you canuse associative arrays with an expansion for missing values. For example:
但是,您可以使用关联数组来扩展缺失值。例如:
declare -A foo
echo "${foo[bar]:-baz}"
This will return "baz" for any missing key. As an alternative, rather than just returning a default value, you can actually setone for missing keys. For example:
这将为任何丢失的键返回“baz”。作为替代方案,您实际上可以为缺少的键设置一个,而不是仅仅返回一个默认值。例如:
echo "${foo[bar]:=baz}"
This alternate invocation will not just return "baz," but it will also store the value into the array for later use. Depending on your needs, either method should work for the use case you defined.
这种替代调用不仅会返回“baz”,还会将该值存储到数组中以备后用。根据您的需要,任何一种方法都应该适用于您定义的用例。
回答by shinkou
Yes, it initiates an empty array and assigns it to MY_ARRAY. You could verify with something like this:
是的,它启动一个空数组并将其分配给MY_ARRAY. 你可以用这样的东西来验证:
#!/bin/bash
declare -a MY_ARRAY=()
echo ${#MY_ARRAY} # this prints out the length of the array

