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

前端 未结 3 1232
情话喂你
情话喂你 2021-01-31 08:19

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==\"\" &&a         


        
3条回答
  •  灰色年华
    2021-01-31 08:51

    If you are ok with writing a function for this purpose, it can be pretty convenient.

    This solution uses the ${!VAR_NAME} syntax to check whether the variable is empty and has the added benefit of telling you which variable names are empty.

    check_vars()
    {
        var_names=("$@")
        for var_name in "${var_names[@]}"; do
            [ -z "${!var_name}" ] && echo "$var_name is unset." && var_unset=true
        done
        [ -n "$var_unset" ] && exit 1
        return 0
    }
    
    # Usage for this case
    check_vars DB HOST DATE
    echo "You are good to go" 
    

提交回复
热议问题