Shell判断字符串是否为空

Shell判断字符串是否为空教程

Shell 中,我们要判断一个字符串是否为空,可以使用 if 条件判断与 test 命令的 z 参数一起进行判断。

Shell判断字符串是否为空详解

语法

if test -z $str then # else # fi

参数

参数 描述
str 需要判断的字符串

说明

我们使用 if 与 test 命令的 z 参数,可以判断字符串是否为空。

案例

Shell判断字符串是否为空

使用 test 命令,实现判断字符串是否为空

#!/bin/bash str1="" str2="HaiCoder" if test -z $str1 then echo "str1 is empty" else echo "str1 is not empty" fi if test -z $str2 then echo "str2 is empty" else echo "str2 is not empty" fi

程序运行后,控制台输出如下:

17_Shell test判断字符串是否为空.png

我们使用了 test 命令与 if 语句,进行了字符串是否为空的判断。

Shell判断字符串是否为空总结

在 Shell 中,我们要判断一个字符串是否为空,可以使用 if 条件判断与 test 命令的 z 参数一起进行判断。