linux判断值相等_linuxSHELL学习之数字比较、字符串比较

1、test

test提供一种检测if-then语句中不同条件的方法,如果test命令中列出的条件评估值为true,test

命令以0

推出状态码退出。

if test condition

then

commands

fi

test命令提供3类条件的评估:数值比较、字符比较、文件比较

数值比较:

n1 -eq n2检查n1是否等于n2         n1 -le n2检查n1是否小于等于n2

n1 -ge n2检查n1是否大于等于n2     n1 -lt n2检查n1是否小于n2

n1 -gt n2检查n1是否大于n2         n1 -ne n2检查n1是否不等于n2

[root@t1 ~]# cat t1.sh

#!/bin/bash

#using numeric test comparisons

var1=10

var2=11

if [ $var1 -lt 5 ]   #注意这里的test与“[”和“]”之间必须要有空格,否则会报错的。

then

echo "the test value $var1 is greater than 5"

fi

if [ $var1 -eq $var2 ]  #注意这里的test与“[”和“]”之间必须要有空格

then

echo "the values are equal"

else

echo "the values are different"

fi

[root@t1 ~]# ./t1.sh

the values are different

字符串比较:

str1 = str2检查str1与str2是否相同       str1 > str2检查str1是否大于str2

str1 != str2检查str1与str2是否不同      -n str1 检查str1的长度是否大于0

str1 < str2检查str1是否小于str2         -z str1 检查str1的长度是否为0

[root@t1 ~]# cat t2.sh  --判断相等否

#!/bin/bash

#testing string eguality

testuser=root

if [ $USER = $testuser ]

then

echo "welcome $testuser"

fi

[root@t1 ~]# ./t2.sh

welcome root

[root@t1 ~]# cat t3.sh   ---不等判断

#!/bin/bash

#tesing string equality

testuser=oracle

if [ $testuser != root ]

then

echo "this is not $testuser"

else

echo "welcome $testuser"

fi

[root@t1 ~]# ./t3.sh

this is not oracle

字符串顺序:

*大于和小于符号一定要转义,否则shell会将他们当做重定向符号,将字符串值看作是文件名。

*大于和小于顺序与在sort中不同

*test使用标准的ASCII排序,使用每个字母的ASCII数值来决定排序顺序,sort命令使用为当前系统语言设置定义的排序顺序。对于英语来说,当前设置指定小写字母排在大写字母之前。

[root@t1 ~]# cat t4.sh

#!/bin/bash

#testing string sort order

var1=Testing

var2=testing

if [ $var1 \> $var2 ]     ---使用标准的ASSCI进行的比较

then

echo "$var1 is greater than $var2"

else

echo "$var1 is less than $var2"

fi

[root@t1 ~]# ./t4.sh

Testing is less than testing

**if [ -n var1 ]判断var1是否为非0值,if [ -z var1 ]判断var1是否为0

[root@t1 ~]# cat t5.sh

#!/bin/bash

#testing string length

var1=testing

var2=''

if [ -n $var1 ]

then

echo "the string '$var1' is not emppty"

else

echo "the  string '$var1' is empty"

fi

if [ -z $var2 ]

then

echo "the string '$var2' is empty"

else

echo "the string '$var2' is not empty"

fi

if [ -z $var3 ]

then

echo "the string '$var3' is empty"

else

echo "the string '$var3' is not empty"

fi

[root@t1 ~]# ./t5.sh

the string 'testing' is not emppty

the string '' is empty

the string '' is empty

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值