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

一、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

猜你喜欢

转载自www.cnblogs.com/97lzc/p/11222010.html