Shell判断字符串是否非空

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

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

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

语法

if test -n $str then # else # fi

参数

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

说明

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

案例

Shell判断字符串是否非空

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

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

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

18_Shell test判断字符串是否非空.png

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

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

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