1、if else (条件判断)
eg:
a=10
b=20
if [ ${a} == ${b} ]
then
echo "a=b"
elif [ ${a} -gt ${b} ]
then
echo "a>b"
else
echo "a<b"
fi
注:若没有else,就不要写else
2、case 语句
eg:
a=10
case ${a} in
10):
echo "a=10"
;;
20):
echo "a=20"
;;
30):
echo "a=30"
;;
esac
注:";;"相当于"break"
3、for 循环
eg1:
eg:
a=10
b=20
if [ ${a} == ${b} ]
then
echo "a=b"
elif [ ${a} -gt ${b} ]
then
echo "a>b"
else
echo "a<b"
fi
注:若没有else,就不要写else
2、case 语句
eg:
a=10
case ${a} in
10):
echo "a=10"
;;
20):
echo "a=20"
;;
30):
echo "a=30"
;;
esac
注:";;"相当于"break"
3、for 循环
eg1:
for i in "I" "am" "a" "fish"
do
printf "%s " ${i}
done
printf "\n"
打印结果:
I am a fish
eg2:
遍历/home下面的文件
for fileName in /home/*
do
echo ${fileName}
done
4、while循环(满足条件则循环)
5、until 语句(不满足条件则循环)
i=0
until [ ${i} -eq 10 ]
do
printf "%d " ${i}
let "i++"
done
printf "\n"
输出:0 1 2 3 4 5 6 7 8 9
6、break/continue 跳出循环
6.1break命令允许跳出所有循环(终止执行后面的所有循环)。
eg:
while :
do
echo -n "Input a number between 1 to 5: "
read aNum #读取键盘输入值
case $aNum in
1 | 2 | 3 | 4 | 5 ) echo "Your number is $aNum!"
;;
*)
echo "You do not select a number between 1 to 5, game is over!"
break #直接跳出while循环
;;
esac
done
注:在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环。例如:
break n
6.2continue 和c语言中的作用一样,不同的是continue后面也可以跟一个数字表示跳出第几层的本次循环
I am a fish
eg2:
遍历/home下面的文件
for fileName in /home/*
do
echo ${fileName}
done
4、while循环(满足条件则循环)
i=0
while [ ${i} -lt 5 ]
do
printf "%d " ${i}
let "i++"
# let 命令是bash用来计算的工具,变量不需要加"$"
done
printf "\n"
输出:1 2 3 4
printf "\n"
输出:1 2 3 4
5、until 语句(不满足条件则循环)
i=0
until [ ${i} -eq 10 ]
do
printf "%d " ${i}
let "i++"
done
printf "\n"
输出:0 1 2 3 4 5 6 7 8 9
6、break/continue 跳出循环
6.1break命令允许跳出所有循环(终止执行后面的所有循环)。
eg:
while :
do
echo -n "Input a number between 1 to 5: "
read aNum #读取键盘输入值
case $aNum in
1 | 2 | 3 | 4 | 5 ) echo "Your number is $aNum!"
;;
*)
echo "You do not select a number between 1 to 5, game is over!"
break #直接跳出while循环
;;
esac
done
注:在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环。例如:
break n
6.2continue 和c语言中的作用一样,不同的是continue后面也可以跟一个数字表示跳出第几层的本次循环