流程控制- if 语句

1.单分支 if 语句

if [ 条件判断式 ];then

  程序

fi

示例代码:

1 #!/bin/bash
2 a=1;b=2    //变量a,b赋值
3 if [ "$a" -gt "$b" ]    //条件判断式1
4   then
5     echo "hell0 work"
6   else
7     echo "good bey"
8 fi    //程序结束

2.双分支 if 条件语句

if [ 条件判断式 ]

  then

    条件成立时候,执行程序

else

    条件不成立时候,执行另外一条程序

示例代码:

 1 #!/bin/bash
 2 date=`date +%y-%m-%d-%H-%M`
 3 size=(du -sh /etc)    //变量 date,size赋值
 4 
 5 if [ -d /tmp/test ]    //条件判断式1
 6         then
 7                 echo "$date is full" > /tmp/test/full.txt
 8                 echo "$size is ok" >> /tmp/test/ok.txt    //程序执行
 9       else
10                 mkdir /tmp/test
11                 echo "$date is full" > /tmp/test/full.txt    //程序执行    
12                 echo "$size is ok" >> /tmp/test/ok.txt
13 fi      //程序结束

3.多分支if条件语句

if [ 条件判断式1 ]

  then

    当条件判断式1成立时候,执行程序1

elif [ 条件判断式2 ]

  then

    当条件判断式2 成立时候,执行程序2

  ...省略更多条件...

else

    当所有条件不成立时候,执行此程序

if

 1 #/bin/bash
 2 echo  "Do you like Chinese or English,please tell me the answer"     //程序开始提示用户输入答案
 3 read 'answer'        //读取变量 answer
 4 if [ $answer == "Chinese" ]    //条件判断式 1
 5         then
 6                 echo "That's really great"
 7         exit 2    //将n的值返回给调用程序,exit方便用户知道运行脚本的情况。程序结束输入echo $? 会返回2
 8 elif [ $answer == "English" ]
 9         then
10                 echo "That's not bad"
11         exit 1
12 else
13         echo "All right"
14 fi
15         exit 0

总结:

1.在[ 条件判断式 ]中,条件判断式都需要用空格隔开。

2.在引用变量或者给变量赋值都需要用 " " 双引号 。 read "answer" if [$answer == "Chinese"]。 

3.在多分支if语句中,elif 后面 需要接 then,而双分支语句else后面则不需要。

猜你喜欢

转载自www.cnblogs.com/lovelitao/p/12315310.html