You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash脚本中判断变量全空或全非空并执行代码

Bash脚本变量判断实现方案

你可以通过两种方式实现需求:要么统计非空变量的数量,要么直接判断所有变量的空值状态是否一致。

方法一:统计非空变量数量

通过计数非空变量的个数,当数量为0(全部为空)或4(全部不为空)时执行代码,这种方式便于后续扩展变量数量:

#!/bin/bash

# 示例变量,可替换为实际值
foo=""
bar=""
baz=""
quax=""

non_empty_count=0
[[ -n "$foo" ]] && ((non_empty_count++))
[[ -n "$bar" ]] && ((non_empty_count++))
[[ -n "$baz" ]] && ((non_empty_count++))
[[ -n "$quax" ]] && ((non_empty_count++))

if [[ $non_empty_count -eq 0 || $non_empty_count -eq 4 ]]; then
    # 这里写入你要执行的代码
    echo "执行目标逻辑..."
fi

方法二:直接判断空值状态

直接写出所有变量为空或全部不为空的条件,逻辑更直观:

#!/bin/bash

# 示例变量,可替换为实际值
foo="test"
bar="demo"
baz="sample"
quax="example"

if [[ ( -z "$foo" && -z "$bar" && -z "$baz" && -z "$quax" ) || ( -n "$foo" && -n "$bar" && -n "$baz" && -n "$quax" ) ]]; then
    # 这里写入你要执行的代码
    echo "执行目标逻辑..."
fi

关键说明

  • -z:判断变量是否为空字符串
  • -n:判断变量是否为非空字符串

内容的提问来源于stack exchange,提问作者starikcetin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:55:01