linux脚本case命令,shell 脚本学习之三 ------if和case 条件语句

shell中的if 和case两个条件语句

1. if的语法1:

if

条件

then

commands

else

commands

fi

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

点击(此处)折叠或打开

#!/bin/bash

#if条件

echo -n "input name"

read user

if

grep $user /etc/passwd>/tmp/null

who -u |grep $user

then

echo "$user has logged"

else

echo "$user has not logged"

fi2.if的语法2:

语法:if 条件

then

commands

elif 条件

then

commands

elif 条件

then

commands

....

else

commands

fi

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

点击(此处)折叠或打开

#!/bin/bash

echo "is it morning ,input yes or no"

read time

if [ "$time" = "yes" ]

then echo "oh,good morning "

elif [ "$time" = "no" ]

then echo "oh, good afterroom"

else

echo "your input is not right"

fi3. 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意思)。

#!/bin/bash

echo -n "input your score"

read score

if   ["$score" -gt 100 -o   "$score" -lt 0 ]

then echo "your score is not corrent"

elif [ "$score" -ge 90 -a   "$score" -le 100 ]

then echo "good 1"

elif [ "$score" -ge 60 -a "$score" -le 70]

then echo "good 4"

elif [ "$score" -ge 70 -a "$score" -le 80]

then echo "good 3"

elif [ "$score" -ge 80 -a "$score" -le 90]

then echo "good 2"

else

echo "bad 5"

fi4. case条件语句:

语法: case 条件 in

xxx)

commands;;

xxx)

commands;;

xxx)

commands;;

esac

说明:这个esac 就是case的结束,想if...fi 一样的,

注意commands;; 中的“;;”不能少掉。

点击(此处)折叠或打开

#!/bin/bash

echo "is it morning ,input yes or no"

read time

case $time in

yes|y)

echo "oh, good morning";;

no|n)

echo "oh, good afternoon";;

*)

echo "oh, your input is not connect"

esac

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值