Bash - 检查数组的每个索引是否有空值

Bash - Checking each index of an array for empty values

使用以下代码,我希望检查数组中的每个索引是否为空值、空字符串或仅包含白色的字符串 space。但是它不起作用。

test=( "apple" "orange" " ")
for i in ${test[@]};
do
    if [ -z "$i" ]; then
        echo "Oh no!"
    fi
done

它永远不会进入 if 块。我做错了什么?

您的脚本中有几个错误

  1. 未引用的数组扩展 for i in ${test[@]};,在此期间只有空格的元素被 shell
  2. 忽略
  3. -z 选项只会检查空字符串而不是带空格的字符串

你需要,

test=( "apple" "orange" " ")
for i in "${test[@]}";
do
    # Replacing single-spaces with empty
    if [ -z "${i// }" ]; then
        echo "Oh no!"
    fi
done

bash 参数扩展语法 ${MYSTRING//in/by}(或)${MYSTRING//in} 在某种程度上是贪婪的,它会替换所有出现的地方。在您的情况下,将所有空格替换为空字符串(空字符串),以便您可以通过 -z

匹配空字符串

在使用 -z 检查时使用空字符串,而不是 space。循环时用 "" 括起 ${array[@]}

test=( "apple" "orange" "")
for i in "${test[@]}";
do
    if [[ -z "$i" ]]; then
        echo "Oh no!"
    fi
done