【Shell】检查字符串大小

-n和-z可以检查变量中是否含有数据,其中:

-n  非空则返回True

-z  如果为空则返回True

例子:

[oracle@master test]$ cat testfile 
#!/bin/bash
# Testing string length
val1=testing
val2=''

if [ -n $val1 ]
then
   echo "The string '$val1' is not empty."
else
   echo "The string '$val2' is empty."
fi

if [ -z val2 ]
then
   echo "The string '$val2' is empty."
else
   echo "The string '$val2' is not empty."
fi

if [ -z $val3 ]
then
   echo "The string '$val3' is empty."
else
   echo "The string '$val3' is not empty."
fi
[oracle@master test]$ sh testfile 
The string 'testing' is not empty.
The string '' is not empty.
The string '' is empty.

总结:

如果不是很确定一个变量是否有值,最好使用-n或者-z检测一下,否则在运行程序时会得到意想不到的结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值