簡單的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!"