bash 检查数组的长度是否等于bash中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13101621/
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
Checking if length of array is equal to a variable in bash
提问by Kr?lleb?lle
I want to check if the length of a bash array is equal to a bash variable (int) or not. My current code looks like this:
我想检查 bash 数组的长度是否等于 bash 变量(int)。我当前的代码如下所示:
if [ "${#selected_columns}" -eq "${number_of_columns}" ]; then
echo "They are equal!"
fi
This returns false since the echo statement is never run. However, doing this produces 4 for both of them:
这将返回 false,因为从不运行 echo 语句。但是,这样做会为它们生成 4 个:
echo "${#selected_columns[@]}"
echo "${number_of_columns}"
What's wrong here? Has it something to do with string versus int?
这里有什么问题?它与字符串与整数有关吗?
采纳答案by sampson-chen
In your:
在你的:
if [ "${#selected_columns}" -eq "${number_of_columns}" ]; then
echo "They are equal!"
fi
${#selected_columns}
is missing [@]
.
${#selected_columns}
不见了[@]
。
Fixed:
固定的:
if [ "${#selected_columns[@]}" -eq "${number_of_columns}" ]; then
echo "They are equal!"
fi
回答by user3226688
According to bash's man page:
根据 bash 的手册页:
${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @, the expansion is the number of elements in the array. Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.
${#name[subscript]} 扩展到 ${name[subscript]} 的长度。如果下标为 * 或 @,则扩展为数组中的元素数。引用一个没有下标的数组变量相当于引用一个下标为 0 的数组。
Using ${name}
on index arrays will result to ${name[0]}
, then you got the length of ${name[0]}
, not counting elements of whole array. So that's not problem about comparing string with integer. AFAIK, comparing "integer number in string" with "integer assigned by let" is never a problem in bash scripting.
${name}
在索引数组上使用将导致${name[0]}
,然后您得到 的长度${name[0]}
,而不是计算整个数组的元素。因此,将字符串与整数进行比较不是问题。AFAIK,将“字符串中的整数”与“由 let 分配的整数”进行比较在 bash 脚本中从来都不是问题。