1. if...elif...else
#!/bin/bash
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "what a fuck"
fi
2. case...esac
echo 'Input a number between 1 to 4'
echo 'Your number is:'
read aNum
case $aNum in
1) echo 'You select 1'
;;
2) echo 'You select 2'
;;
3) echo 'You select 3'
;;
4) echo 'You select 4'
;;
*) echo 'You do not select a number between 1 to 4'
;;
esac
[root@localhost shell_study]# ./test6.sh
Input a number between 1 to 4
Your number is:
2
You select 2
表达方式:
1|2|3|4|5) echo "Your number is $aNum!"
;;
3. for循环
for value in 1 2
do
echo "The value is: $value"
done
输出:
The value is: 1
The value is: 2
for str in 'This is a string'
do
echo $str
done
输出:
This
is
a
string
for FILE in $HOME/.bash*
do
echo $FILE
done
遍历当前用户HOME目录下以.bash结尾的所有文件
4. while循环
#!/bin/bash
i=1
while ((i<10))
do
echo "$i"
i=`expr $i + 1`
done
5. 跳出循环
#!/bin/bash
for var1 in 1 2 3
do
for var2 in 4 5
do
if ((var1 == 2 && var2 == 5))
then
break 2
else
echo "内层循环:$var1 $var2"
fi
done
echo "外层循环:$var1"
done
[root@localhost shell_study]# ./test.sh
内层循环:1 4
内层循环:1 5
外层循环:1
内层循环:2 4
注意:
- if elif后面必须有then
- []与变量之间必须有空格
- 当变量是数字时,可用表达式:
if [ $a == $b ]
if [ a == b ]
if ((a == b))
if [ $a -gt $b ]
if [ $a -lt $b ]
if [ a > b ]
if ((a < b))
if ((a == b && a > 0))
if ((a == b || a > 0))
- 当变量是字符串时,可用表达式:
if [ $a == $b ]
if [ a == b ]
if [ a == b -a a == "love" ]
if [ a == b -o a == "love" ]
if ((a == b && a == "love"))
if ((a == b || a == "love"))