首页 > 解决方案 > Nested If else Statement, operand expected

问题描述

If else statement nested in for loop. Operand expected. error token is:

Ubuntu Linux

for i in "${dir_path[@]}"; do
  if [ "$dir_path[i]" ]; then     <--- this line
     echo "$filename found, Directory: $i"
  else
     echo "$filename not found"
  fi
done

It finds the paths correctly but it displays error: "operand expected (error token is "first directory"

标签: bash

解决方案


要遍历数组的索引,请使用

for i in "${!dir_path[@]}" ; do
#           ^

要检查文件是否存在,请使用[ -f "${dir_path[i]}" ](对于数组,或与$i关联数组相同)。你所拥有的总是正确的,因为它检查字符串"$dir_path[i]"是否不为空,它永远不会是,因为它总是至少包含[i].


推荐阅读