if控制语句字符比较

== 等于则条件为真

!= 不等于条件则为真

-z      判断值是否为空,为空则为真,字符串的长度为零

-n      判断字符串的长度不为零则为真

字符比较要用双引号括起来

[root@shell /scripts]# echo $USER

root

[root@shell /scripts]# echo $SHELL

/bin/bash

[root@shell /scripts]# [ "$USER" == "root" ] && echo "为真"  || echo "为假"

为真

[root@shell /scripts]# [ "$USER" == "roott" ] && echo "为真"  || echo "为假"

为假

[root@shell /scripts]# [ "$USER" != "roott" ] && echo "为真"  || echo "为假"

为真

[root@shell /scripts]# [ "$USER" != "root" ] && echo "为真"  || echo "为假"

为假

[root@shell /scripts]# name=""

[root@shell /scripts]# echo ${#name}

0

[root@shell /scripts]# [ -z $name ] && echo "为真"  || echo "为假"

为真

[root@shell /scripts]# name=1

[root@shell /scripts]# echo ${#name}

1

[root@shell /scripts]# [ -z $name ] && echo "为真"  || echo "为假"

为假

[root@shell /scripts]# [ -n $name ] && echo "为真"  || echo "为假"

为真

[root@shell /scripts]# cat yes.sh

#!/bin/bash

read -p "请输入一组字符串(如:yes或者no):" Zf

if [ "$Zf" == "yes" ];then

    echo "你输入的是yes"

elif [ "$Zf" == "no" ];then

    echo "你输入的是no"

else

    echo "你输入的不正确"

fi

[root@shell /scripts]# sh yes.sh

请输入一组字符串(如:yes或者no):yes

你输入的是yes

[root@shell /scripts]# sh yes.sh

请输入一组字符串(如:yes或者no):no

你输入的是no

[root@shell /scripts]# sh yes.sh

请输入一组字符串(如:yes或者no):yess

你输入的不正确

[root@shell /scripts]# sh yes.sh

请输入一组字符串(如:yes或者no):noo

你输入的不正确

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容