Chinaunix首页 | 论坛 | 博客
  • 博客访问: 924085
  • 博文数量: 376
  • 博客积分: 154
  • 博客等级: 入伍新兵
  • 技术积分: 1558
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-13 08:42
文章分类

全部博文(376)

文章存档

2014年(11)

2013年(88)

2012年(260)

2011年(17)

分类:

2012-04-06 18:18:28

shell中的if 和case两个条件语句
1. if的语法1
    if
    条件
    then
    commands
    else
    commands
    fi

   说明:条件中可以不止一条语句,如果有多条语句的话,相当于 and 连接起来。(例子来源麦子屋)

点击(此处)折叠或打开

  1. #!/bin/bash
  2. #if条件
  3. echo -n "input name"
  4. read user
  5. if
  6. grep $user /etc/passwd>/tmp/null
  7. who -u |grep $user
  8. then
  9. echo "$user has logged"
  10. else
  11. echo "$user has not logged"
  12. fi
2.if的语法2
  语法:if 条件
        then
          commands
        elif 条件
        then
           commands
        elif 条件
        then
            commands
        ....
        else
           commands
        fi

        说明:read  是读取用户输入的一行

点击(此处)折叠或打开

  1. #!/bin/bash

  2. echo "is it morning ,input yes or no"
  3. read time
  4. if [ "$time" = "yes" ]
  5. then echo "oh,good morning "
  6. elif [ "$time" = "no" ]
  7. then echo "oh, good afterroom"
  8. else
  9. echo "your input is not right"
  10. fi
3. if语句的一些说明
   首先:
if 条件1
        then
          commands
        elif 条件2
        then
           commands
        elif 条件3
        then
            commands
        ....
        else
           commands
        fi
中的条件1,2,3等,都是同等地位的,也就是相当于条件1不满足,则看条件2,条件1、2都不满足,则看条件3 以此往下推(-a 为and的意思,但是不能用&&替代
,否则会报错,-o 为or意思)。


  1. #!/bin/bash

  2. echo -n "input your score"
  3. read score
  4. if   ["$score" -gt 100 -o   "$score" -lt 0 ]
  5. then echo "your score is not corrent"
  6. elif [ "$score" -ge 90 -a   "$score" -le 100 ]
  7. then echo "good 1"
  8. elif [ "$score" -ge 60 -a "$score" -le 70]
  9. then echo "good 4"
  10. elif [ "$score" -ge 70 -a "$score" -le 80]
  11. then echo "good 3"
  12. elif [ "$score" -ge 80 -a "$score" -le 90]
  13. then echo "good 2"
  14. else
  15. echo "bad 5"
  16. fi
4. case条件语句
   语法: case 条件 in
          xxx)
          commands;;
          xxx)
          commands;;
          xxx)
          commands;;
          esac

   说明:这个esac 就是case的结束,想if...fi 一样的,
         注意commands;; 中的“;;”不能少掉。

点击(此处)折叠或打开

  1. #!/bin/bash

  2. echo "is it morning ,input yes or no"
  3. read time

  4. case $time in
  5. yes|y)
  6. echo "oh, good morning";;
  7. no|n)
  8. echo "oh, good afternoon";;
  9. *)
  10. echo "oh, your input is not connect"
  11. esac



     
  

阅读(447) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~