首页 > 其他 > 详细

if, if/else, if /elif/else,case

时间:2019-07-21 18:43:54      阅读:58      评论:0      收藏:0      [点我收藏+]

一、if语句用法

if expression

then

command

fi

 

例子:使用整数比较运算符

read -p "please input a integer:" a

if [ "$a" -gt  10 ]

then

echo "The integer which you input is bigger than 10。"

exit 100

fi

备注:执行脚本后,exit 命令可以返回退出状态, echo $?可以打印退出状态

 

二、if/else语句用法

if expression

then

command

else 

command

fi

 

例子:判断文件是否存在。

if  [ -e "$1"]   #$1是位置参数

then

echo "the file $1 is exist"

else

echo "the file is $1 not exist"

fi

 

 

三、if/elif/else语句用法

if expression1

then

command

elif expression2

then

command

elif expression3

then

command

else

command

fi

 

例子:输入分数,判断分数等级

#!/bin/bash
read -p "please input your score:" s
if [ "$s" -ge 90 ]
then
echo "The grade is A!"
exit 1
elif [ "$s" -ge 80 ]
then
echo "The grade is B!"
exit 2
elif [ "$s" -ge 70 ]
then
echo "The grade is C!"
exit 3
elif [ "$s" -ge 60 ]
then
echo "The grade is D!"
exit 4
else
echo "The grade is E!"
exit 5
fi

//运行实例

[root@localhost lzic]# ./a.sh
please input your score:90
The grade is A!
[root@localhost lzic]# echo $?
1
[root@localhost lzic]# ./a.sh
please input your score:20
The grade is E!
[root@localhost lzic]# echo $?
5

三、case用法

case variable in 

value1)

command

value2)

command

value3)

command

*)

command

esac

 

if, if/else, if /elif/else,case

原文:https://www.cnblogs.com/97lzc/p/11222010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!