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"
- fi
2.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"
- 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意思)。- #!/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"
- fi
4. 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
阅读(918) | 评论(0) | 转发(0) |