检查环境变量
Contents
1. 概述
作为 Linux 用户,我们经常使用 shell 脚本。脚本中的常见要求之一是测试是否设置了特定的环境变量。这有助于处理各种错误情况。
在本教程中,我们将看到各种示例来检查是否设置了特定的环境变量。
2. 使用if条件表达式
我们可以使用if 条件表达式 来检查是否将值分配给变量:
$ VAR=
$ if [ x"${VAR}" == "x" ]; then
echo "Value is not assigned to a variable"
else
echo "Value is assigned to a variable"
fi
Value is not assigned to a variable
让我们为变量赋值并验证结果:
$ VAR="sample-value"
$ if [ x"${VAR}" == "x" ]; then
echo "Value is not assigned to a variable"
else
echo "Value is assigned to a variable"
fi
Value is assigned to a variable
3. 使用双方括号
检查变量是否设置的另一种方法是使用双方括号:
$ VAR=
$ [[ x"${VAR}" == "x" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable
让我们通过为变量赋值来验证输出:
$ VAR="sample-value"
$ [[ x"${VAR}" == "x" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable
请注意,此方法仅适用于 Bash、Z Shell (zsh) 和 Korn Shell (ksh)。
4. 使用参数表达式
我们可以使用bash 内置参数表达式 来检查是否设置了变量:
$ VAR=
$ [[ ${VAR:-"unset"} == "unset" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable
让我们设置一个变量的值并检查它是否有效:
$ VAR="sample-value"
$ [[ ${VAR:-"unset"} == "unset" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable
5. 使用*-z*条件表达式
在bash中,有一个-z条件表达式,如果字符串的长度为零,则返回true 。**我们可以使用这个属性来检查一个变量是否被设置:
$ VAR=
$ [[ -z "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable
让我们试一试:
$ VAR="sample-value"
$ [[ -z "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable
6. 使用*-n*条件表达式
类似地,如果字符串的长度不为零,则-n条件表达式返回true 。**我们可以使用这个属性来检查一个变量是否被设置:
$ VAR=
$ [[ ! -n "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable
让我们更新一个变量的值并确认结果:
$ VAR="sample-value"
$ [[ ! -n "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable