如何在Bash中检测字符串是否为空/未设置或不匹配指定值?
Your current condition has a logical flaw that makes it always evaluate to true. Let's break it down and fix it.
The Problem with Your Original Code
if [[ -z $DEP_FLAVOUR || $DEP_FLAVOUR != "develop" || $DEP_FLAVOUR != "release" ]]; then
Using || (OR) between $DEP_FLAVOUR != "develop" and $DEP_FLAVOUR != "release" means one of these two conditions will always be true:
- If
DEP_FLAVOURisdevelop, the third condition (!= "release") is true. - If
DEP_FLAVOURisrelease, the second condition (!= "develop") is true. - If it's anything else, both are true.
So the entire if block will run no matter what the variable's value is.
Correct Solutions
Option 1: Fix the Logical Operators
You need to check if the variable is empty OR (it's not develop AND not release). Use && for the two "not equal" checks, and wrap them in parentheses to group the logic:
if [[ -z $DEP_FLAVOUR || ($DEP_FLAVOUR != "develop" && $DEP_FLAVOUR != "release") ]]; then # Your code here for invalid/empty values fi
Option 2: Use a case Statement (More Readable)
For condition checks against multiple allowed values, case is often clearer and easier to maintain:
case "$DEP_FLAVOUR" in develop|release) # Code to run if value is valid (optional) ;; *) # Code to run if value is empty or invalid ;; esac
Option 3: Regular Expression Match
You can also use Bash's regex matching to check if the variable matches either allowed value, then negate the check:
if [[ -z $DEP_FLAVOUR || ! $DEP_FLAVOUR =~ ^(develop|release)$ ]]; then # Your code here for invalid/empty values fi
Key Notes
- Always double-check logical operators (
||vs&&) when combining conditions—they're easy to mix up. - Quoting variables like
"$DEP_FLAVOUR"is a good habit to avoid issues with spaces or special characters, though[[ ]]handles unquoted variables more safely than[ ].
内容的提问来源于stack exchange,提问作者DanDan

