shell中的if判断语句

一、语法

if [ condition ]
then 
    statements 
[elif condition 
    then statements. ..] 
[else 
    statements ] 
fi

二、说明

(1)[ condition ] ( 注意 condition 前后要有空格 )
非空返回true,可使用$?验证(0为true,>1为false) 如:[ hadoop ] 返回true
空返回false 如:[  ] 返回false
(2)[ condition ] && echo OK ||echo notok 可以多条件,条件满足,执行后面的语句

三 、示例

[root@localhost shell]# vi testif.sh
#/bin/bash
if [ $USER=root ]
   then
      echo "hello $USER"
 elif [ $USER=hadoop ]
   then
        echo " welcome $USER"
 else
    echo "hi $USER"
fi
~
"testif.sh" 11L, 147C written
[root@localhost shell]# chmod +x testif.sh 
[root@localhost shell]# ./testif.sh 
hello root
[root@localhost shell]# 
四、 常用的判断条件

=字符串比较
-lt小于
-le小于等于
-eq等于
-gt大于
-ge大于等于
-ne不等于
-r有读的权限
-w有写的权限
-x有执行的权限
-f文件存在并且是一个常规的文件
-s文件存在且不为空
-d文件存在并是一个目录
-b文件存在并且是一个块设备
-L文件存在并且是一个软连接

示例:

[root@localhost shell]# vi testif2.sh
#/bin/bash
if [ -x testif.sh ]
        then
        echo " have x"
  else 
    echo " doesn't have x"
fi

if [ 3 -lt 4 ]
   then 
        echo "less"
   else
        echo "more"
fi

if [ $user=root ]
   then 
        echo "root"
   else
        echo "other"
fi
~
"testif2.sh" [New] 21L, 219C written
[root@localhost shell]# chmod +x testif2.sh 
[root@localhost shell]# ./testif2.sh
 have x
less
root
[root@localhost shell]# 





  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值