我尝试获取数组长度有什么问题? [英] What is wrong with my attempt to get the length of an array?
问题描述
脚本具有以下内容:
#/bin/bash
path_elements=$(echo $PATH | tr ":" " ")
echo ${#path_elements[*]}
我的PATH变量包含几个目录.但是,运行时,输出返回:
My PATH variable contains several directories. However, when run, the output returns:
1
为什么这不返回$ PATH中的目录数?要解决此问题需要什么?
Why isn't this returning the number of directories in $PATH? What is needed to fix this?
推荐答案
您正在读入单个字符串,其中的空格代替冒号(而文字制表符则替换为空格,并且扩展了glob表达式,以及其他各种行为)您可能不想要);因此,当您询问数组 path_elements
中存在多少个字符串时,您会得到答案1,因为只有一个字符串(根本没有数组).
You're just reading into a single string with spaces in place of colons (and literal tab characters replaced with spaces, and glob expressions expanded, and various other behaviors you probably don't want); thus, when you ask how many strings exist in the array path_elements
, you get the answer 1, because there's only one string (not an array at all).
现在,此是一个数组,也是读取该数组的最佳实践方法:
Now, this is an array, and a best-practices way to read into it:
# This is the best-practices approach.
IFS=: read -r -a path_elements <<<"$PATH"
echo "${#path_elements[@]}"
...这是一种不正确的,错误的方式来读入数组(至少确实创建了一个数组-但不能正确处理带有空格的目录名称,错误地扩展glob并导致一堆错误)问题):
...and this is an incorrect, buggy way to read into an array (that does, at least, create an array -- but doesn't handle directory names with spaces correctly, incorrectly expands globs, and causes a bunch of problems):
# This is a buggy antipattern that does, at least, create an array
path_elements=( $(tr ':' ' ' <<<"$PATH") )
echo "${#path_elements[@]}"
有关正确使用数组的更多信息,请参见 BashFAQ#5 .
这篇关于我尝试获取数组长度有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!