如果语句具有多个空字符串比较,则打印错误与失败的错误

时间:2016-06-26 12:38:37

标签: bash if-statement

假设我有以下if语句检查多个变量

if [[ -z ${var1} || -z ${var2} || -z ${var3} ]]; then
   echo "Error, one or more variables are empty"
   exit 2
fi

我正在寻找一种可以进行相同测试的方法,但不知何故能够打印出空的确切变量,如下所示:

if [[ -z ${var1} || -z ${var2} || -z ${var3} ]]; then
   echo "Error, the following variables are empty: ${var1} and ${var3}"
   exit 2
fi

当然,我可以单独测试它们:

if [[ -z ${var1} ]]; then
   echo "Error, the following variable is empty: ${var1}"
   exit 2
fi
if [[ -z ${var2} ]]; then
   echo "Error, the following variable is empty: ${var2}"
   exit 2
fi
if [[ -z ${var3} ]]; then
   echo "Error, the following variable is empty: ${var3}"
   exit 2
fi

但是这个方法也有一个很大的缺陷:如果有多个空变量,脚本将在第一个之后退出,你永远不会知道其他人也是空的。

3 个答案:

答案 0 :(得分:3)

使用间接扩张的一种可能性:

empty=()
for i in var1 var2 var3; do
    [[ -z ${!i} ]] && empty+=( "$i" )
done

if ((${#empty[@]})); then
    echo "Error, the following variables are empty: ${empty[*]}"
    exit 2
fi

检查变量的循环的优点是您不必重复代码。

答案 1 :(得分:1)

不要立即执行exit 2,而是设置一个标记(比如error=1),然后在第三个if之后添加以下内容:

[[ $error ]] && exit 2

你也可以使用循环而不是手动重复所有这些ifecho s:

for varname in var1 var2 var3
do
    if [[ -z "${!varname}" ]]
    then
        echo "Error, the following variable is empty: $varname"
        error=1
    fi
done

[[ $error ]] && exit 2

答案 2 :(得分:0)

您可以像这样合并代码:

if [[ -z ${var1} ]]; then
    echo "Error, the following variable is empty: ${var1}"
fi
if [[ -z ${var2} ]]; then
   echo "Error, the following variable is empty: ${var2}"
fi
if [[ -z ${var3} ]]; then
   echo "Error, the following variable is empty: ${var3}"
fi

if [[ -z ${var1} || -z ${var2} || -z ${var3} ]]; then
   exit 2
fi