shell 脚本中判断一个 bash 变量是否为空字符串

shell 2020-06-14 阅读 2308 评论 0

使用 bash 脚本,有时候需要判断字符串变量的值,是否为空。下面介绍2种比较简单的方法。

-n 运算符

-n 是受支持的 bash 字符串比较运算符之一,用于检查 bash 脚本中的空字符串。如果变量包含字符(长度大于0)则返回 true,即使是一个空格符号也为真,如果为空字符串,则返回 false

#!/bin/bash
str1="hello world"
if [[ -n "$str1" ]]; then
    echo "str1 is not empty"
fi
str2=""
if [[ ! -n "$str2" ]]; then
    echo "str2 is empty"
fi

输出

str1 is not empty
str2 is empty

-z 运算符

-z 是第二个受支持的 bash 字符串比较运算符,用于检查字符串是否为空。 -z 运算符的功能类似于 -n 运算符。下面是一个示例:

#!/bin/bash
str=""
if [[ -z "$str" ]]; then
    echo "str is empty"
fi

输出

str is empty

示例

以下是一个示例,判断输入的第一个参数是否为空。

isempty.sh 文件:

#!/bin/bash
str=$1
[[ -n "$str" ]] && echo "第1个参数为:$str" || echo "第1个参数为空"
[[ -z "$str" ]] && echo "第1个参数为空" || echo "第1个参数为:$str"

运行示例:

$ ./isempty.sh   
第1个参数为空
第1个参数为空
$ ./isempty.sh hello
第1个参数为:hello
第1个参数为:hello
最后更新 2020-06-15