如何检查bash中是否定义了多个变量 [英] How to check if multiple variables are defined or not in bash
问题描述
我想检查是否设置了多个变量,如果设置了则仅执行脚本代码,否则退出.
I want to check, if multiple variable are set or not, if set then only execute the script code, otherwise exit.
类似:
if [ ! $DB=="" && $HOST=="" && $DATE=="" ]; then
echo "you did not set any variable"
exit 1;
else
echo "You are good to go"
fi
推荐答案
您可以使用 -z
来测试变量是未设置还是空:
You can use -z
to test whether a variable is unset or empty:
if [[ -z $DB || -z $HOST || -z $DATE ]]; then
echo 'one or more variables are undefined'
exit 1
fi
echo "You are good to go"
使用了 bash 标签的问题后,我使用了扩展测试 [[
",这意味着我不需要在变量周围使用引号.我假设您需要定义所有三个变量才能继续. if
分支中的 exit
表示 else
是多余的.
As you have used the bash tag, I've used an extended test [[
, which means that I don't need to use quotes around my variables. I'm assuming that you need all three variables to be defined in order to continue. The exit
in the if
branch means that the else
is superfluous.
在任何符合POSIX的外壳中执行此操作的标准方法如下:
The standard way to do it in any POSIX-compliant shell would be like this:
if [ -z "$DB" ] || [ -z "$HOST" ] || [ -z "$DATE" ]; then
echo 'one or more variables are undefined'
exit 1
fi
此处的重要区别在于,每个变量检查都在单独的测试中进行,并且每个参数扩展都使用双引号.
The important differences here are that each variable check goes inside a separate test and that double quotes are used around each parameter expansion.
这篇关于如何检查bash中是否定义了多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!