在Bash脚本中如何判断变量是否为空

下面的bash脚本示例演示了如何使用bash检查空变量或者null变量:

#!/bin/bash 
if [ -z "$1" ]; then
    echo "Empty Variable 1"
fi

if [ -n "$1" ]; then
    echo "Not Empty Variable 2"
fi

if [ ! "$1" ]; then
    echo "Empty Variable 3"
fi

if [ "$1" ]; then
    echo "Not Empty Variable 4"
fi

[[ -z "$1" ]] && echo "Empty Variable 5" || echo "Not empty Variable 5"

将上述脚本保存到“check_empty.sh”中,并不带命令行参数执行:

$bash check_empty.sh 
Empty Variable 1
Empty Variable 3
Empty Variable 5

带参数执行:

$bash check_empty.sh hello
Not Empty Variable 2
Not Empty Variable 4
Not empty Variable 5
日期:2020-07-07 20:54:44 来源:oir作者:oir