在 shell 中,可以使用以下三种方式来判断一个变量是否为空:

  1. 使用 if 语句
if [ -z '$variable' ]; then
    echo 'Variable is empty'
else
    echo 'Variable is not empty'
fi
  1. 使用 test 命令
if test -z '$variable'; then
    echo 'Variable is empty'
else
    echo 'Variable is not empty'
fi
  1. 使用双括号
if [[ -z '$variable' ]]; then
    echo 'Variable is empty'
else
    echo 'Variable is not empty'
fi

其中,-z 表示判断字符串长度是否为 0,如果是则表示变量为空。'$variable' 表示要判断的变量名。


原文地址: https://www.cveoy.top/t/topic/lTXe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录