脚本具有以下内容:
#/bin/bash
path_elements=$(echo $PATH | tr ":" " ")
echo ${#path_elements[*]}
我的 PATH 变量包含多个目录。但是,运行时,输出返回:
1
为什么这不返回 $PATH 中的目录数量?需要什么来解决这个问题?
最佳答案
您只是读入一个字符串,用空格代替冒号(用空格替换文本制表符,扩展全局表达式,以及您可能不想要的各种其他行为);因此,当您询问数组 path_elements
中存在多少个字符串时,您会得到答案 1,因为只有一个字符串(根本不是数组)。
现在,这是是一个数组,也是读取它的最佳实践方法:
# This is the best-practices approach.
IFS=: read -r -a path_elements <<<"$PATH"
echo "${#path_elements[@]}"
...这是一种不正确的、有缺陷的读入数组的方法(至少创建了一个数组 - 但不能正确处理带有空格的目录名称,错误地扩展全局变量,并导致一堆问题):
# This is a buggy antipattern that does, at least, create an array
path_elements=( $(tr ':' ' ' <<<"$PATH") )
echo "${#path_elements[@]}"
参见BashFAQ #5有关正确使用数组的更多信息。
关于arrays - 我尝试获取数组长度有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30380903/