bash 如何检查是否在bash中定义了多个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29278743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:54:24  来源:igfitidea点击:

How to check if multiple variables are defined or not in bash

bashshell

提问by ramesh.mimit

I want to check, if multiple variable are set or not, if set then only execute the script code, otherwise exit.

我想检查一下,是否设置了多个变量,如果设置了则只执行脚本代码,否则退出。

something like:

就像是:

if [ ! $DB=="" && $HOST=="" && $DATE==""  ]; then
  echo "you did not set any variable"
   exit 1;
else
  echo "You are good to go"
fi      

回答by Tom Fenech

You can use -zto test whether a variable is unset or empty:

您可以使用-z来测试变量是否未设置或为空:

if [[ -z $DB || -z $HOST || -z $DATE ]]; then
  echo 'one or more variables are undefined'
  exit 1
fi

echo "You are good to go"

As you have used the bashtag, 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 exitin the ifbranch means that the elseis superfluous.

由于您使用了bash标记,因此我使用了扩展 test [[,这意味着我不需要在我的变量周围使用引号。我假设您需要定义所有三个变量才能继续。将exitif分支构件的else是多余的。

The standard way to do it in any POSIX-compliant shell would be like this:

在任何符合 POSIX 的 shell 中执行此操作的标准方法如下:

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.

这里的重要区别是每个变量检查​​都在单独的测试中,并且每个参数扩展都使用双引号。

回答by Chetabahana

You can check it also by put the variables name in a file

您也可以通过将变量名称放在文件中来检查它

DB=myDB
HOST=myDB
DATE=myDATE

then test them if currently emptyor unset

然后测试它们是否当前emptyunset

#!/bin/bash
while read -r line; do
    var=`echo $line | cut -d '=' -f1`
    test=$(echo $var)
    if [ -z "$(test)" ]; then 
        echo 'one or more variables are undefined'
        exit 1
    fi
done <var.txt
echo "You are good to go"