注:此博客使用的是Bash shell
if语句
- if
if condition
then
command1
command2
...
commandN
fi
- if else
if condition
then
command1
command2
...
commandN
else
command
fi
- if else-if else
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
for循环
- ①
for var in vaule1 value2 ... valueN
do
command
done
- ②注意分号,for()里面用变量的时候,无需加$。但是,command里面用变量需要添加 $。
for((i=1;i<10;i++));do
conmmand;
done;
while
temp=${1}
while [ ${temp} -gt 1 ]
do
temp=`expr ${temp} - 1 `
echo "${temp}"
done
无限循环
- ①
while :
do
command
done
- ②
while true
do
command
done
until循环
- until 循环执行一系列命令直至条件为 true 时停止
- until 循环与 while 循环在处理方式上刚好相反
- 一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用
#!/bin//bash
temp=${1}
until [ ${temp} -le 10 ]
do
temp=`expr ${temp} - 1 `
echo "${temp}"
done
cjs@Queue:~$ ./obj.sh 20
19
18
17
16
15
14
13
12
11
10
case
- 类似C里面的switch
#!/bin/bash
read temp
case ${temp} in
1) echo "1"
;;
2) echo "2"
;;
*) echo "无"
;;
esac
跳出循环
- break命令(同C语言)
#!/bin/bash
while true
do
echo "please input num"
read temp
case ${temp} in
1|2|3|4|5) echo "cout ${temp}"
;;
*) echo "this is great than 5"
break #可以直接跳出while
;;
esac
done
cjs@Queue:~$ ./obj.sh
please input num
1
cout 1
please input num
2
cout 2
please input num
3
cout 3
please input num
4
cout 4
please input num
5
cout 5
please input num
6
this is great than 5
- continue(同C语言)
#!/bin/bash
while true
do
echo "please input num"
read temp
case ${temp} in
1|2|3|4|5) echo "cout ${temp}"
;;
*) echo "this is great than 5"
continue #直接结束本次循环,开始下一次循环
echo "over" #永远也无法运行到这句
;;
esac
done