简单的if 结构
if expression
then
command
command
……
fi
测试条件后没有“;”,则 then 语句要换行。 if 和 then 处于同一行,必须用“;”来终止 if 语句
if expression ; then
command
……
fi
举例说明:
#!/bin/bash
echo "Please input a integer: "
read integer1
if [ "$integer1" -lt 15 ] ; then
echo "The integer which you input is lower than 15."
fi
exit 命令
exit status # status 用 0~255 之间的数字表示 ,exit 不能在终端运行。
举例说明 :
[root@localhost tmp]# cat 2.sh
#!/bin/bash
echo "Please input a string: "
read str1
if [ -z "$str1" ]
then
echo "What you input is null!"
exit 1
fi
[root@localhost tmp]# ./2.sh
Please input a string:
hello
[root@localhost tmp]# echo $?
0
[root@localhost tmp]# ./2.sh
Please input a string:
What you input is null!
[root@localhost tmp]# echo $?
1
[root@localhost tmp]#
if/else 结构
if expression
then
command
……
else
command
……
fi
举例说明:(例一)
[root@localhost tmp]# cat 3.sh
#!/bin/bash
file=/tmp/3.sh
if [ ! -e "$file" ]
then
echo "file $file do not exist ."
exit
else
echo "file $file exist ."
fi
[root@localhost tmp]# ./3.sh
file /tmp/3.sh exist .
[root@localhost tmp]#
举例说明:(例二)
#!/bin/bash
echo "Please input the file which you want to delete:"
read file
if rm -f "$file"
then
echo "Delete the file $file sucessfully!"
else
echo "Delete the file $file failed!"
fi
if/else 语句嵌套
if expression1
then
if expression2
then
command
else
command
fi
else
if expression3
then
command
else
command
fi
fi
举例说明:
#!/bin/bash
echo "Please input a file_name:"
read word
if [ "$word" ]
then
echo "What you input is not null!"
if [ -e "$word" ]
then
echo "The file $word is existence !"
else
echo "The file $word is not existence !"
fi
else
echo "what you input is null!"
fi
if/elif/else 结构
if expression1
then
command
elif expression2
then
command
elif expressionN
command
else
command
fi
举例说明
#!/bin/bash
echo "Please Input a integer(0-100): "
read score
if [ "$score" -lt 0 -o "$score" -gt 100 ]
then
echo "The score what you input is not integer or the score is not in (0-100)."
elif [ "$score" -ge 90 ]
then
echo "The grade is A!"
elif [ "$score" -ge 80 ]
then
echo "The grade is B!"
elif [ "$score" -ge 70 ]
then
echo "The grade is C!"
elif [ "$score" -ge 60 ]
then
echo "The grade is D!"
else
echo "The grade is E!"
fi
case 结构
case variable in
value1)
command
……
command;;
Value2)
command
command;;
……
valueN)
command
……
command;;
*)
command
command;;
esac
举例说明 :
#!/bin/bash
echo "Please Input a month(0-12): "
read month
case "$month" in
1)
echo "The month is January!";;
2)
echo "The month is February!";;
3)
echo "The month is March!";;
4)
echo "The month is April!";;
5)
echo "The month is May!";;
6)
echo "The month is June!";;
7)
echo "The month is July!";;
8)
echo "The month is August!";;
9)
echo "the month is September!";;
10)
echo "The month is October!";;
11)
echo "The month is November!";;
12)
echo "The month is December!";;
*)
echo "The month is not in (0-12)";;
esac
echo "The 'case' command ends!"