Shell 编程5(条件判断语句if)

1简单的if结构是:

      if  expression

      then           command          command           …

     fi

eg 判断脚本 参数个数是否为0

#!/bin/bash
function usage()
{
 echo "must have a param"
 echo "usage $0 param"
}

if [ $# = 0 ]
 then 
 usage
 exit 1
fi

echo $#
exit 0


eg2  脚本只能由root用户执行

#!/bin/bash

if [ $UID != "0" ]
 then 
 echo "must use root user to execute it . . . . ."
 exit 1
fi

echo "you are root , you can execute it!"

运行结果:

anders@anders-virtual-machine:~/code/shell/if$ ./if2.sh 
must use root user to execute it . . . . .
anders@anders-virtual-machine:~/code/shell/if$ sudo ./if2.sh 
you are root , you can execute it!

2 if else

命令是双向选择语句,当用户执行脚本时如果不满足if后的表达式也会执行else后的命令,所以有很好的交互性。其结构为:
       if expression1
       then 
              command
              …
              command
        else 
              command
              …
              command
        fi

eg

#!/bin/bash

if [ -w test ]
 then 
 cat tmp >> test
 echo "put tmp file into test file"
 rm -r tmp
 exit 0
else 
 echo "test has no write privilege"
 exit 1
fi

3 if   elif 多条件检测

 if expression1
    then    
         command                                               
         command
         …
    elif expression2
    then
         command
        command
        …
elif expressionN
then
    command
    …
    command
else 
   command
    …
   command
fi

#!/bin/bash
function usage()
{
 echo "error must have a param"
 echo "usage $0 filename"
}

if [ $# = 0 ]
 then 
 usage 
 exit 1
fi

if [ -d $1 ]
 then
 echo -n "Sure you want to delete the directory?[yes | no]"
 read ANS
 if [ $ANS = "yes"]
   then 
   rm -rf $1 &>/dev/null
   exit 0
 elif [ $ANS = "no" ]
   then 
   exit 0
 else
   echo "input error!"
   exit
 fi
else
  echo -n "Sure you want to delete the file?[yes|no]"
  read ANS
  if [ $ANS = "yes" ]
     then 
     rm -rf $1 &>/dev/null
  fi
fi

4 case 多条件判断语句

和if/elif/else结构一样,case结构同样可用于多分支选择语句,常用来根据表达式的值选择要执行的语句,该命令的一般格式为: 

caseVariable  in

value1)

    command

command;;

value2)

    command

   

    command;;

valueN)

     command

    

     command;;

*)

      command

     

      command;;

esac


#!/bin/bash
echo "enter today:"
read today

case $today in
 monday)
 echo "1"
 ;;
 sunday)
 echo "2"
 ;;
 friday)
 echo "3"
 ;;
esac



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值