基本流程控制
1. if
语句
语法:
if condition
thencommand1command2...
fi
单行写法:
if ((4<5));then printf "4<5";fi
# printf :4<5
2. if-else
语句
语法:
if condition
thencommand1
elsecommand2
fi
3. if-elif-else
语句
语法:
if condition1
thencommand1
elif condition2
thencommand2
elsecommand3
fi
示例:
num_1=9if ((4<5));then printf "num_1<5"
elif ((num_1<10)); thenprintf "num_1<10"
else printf "other case"
fi # printf: num_1<5
判断语句的写法
-
使用
[...]
:- 大于:
-gt
- 小于:
-lt
- 等于:
-eq
if [ "$a" -gt "$b" ]; then echo "a > b"; fi
- 大于:
-
使用
((...))
:- 大于:
>
- 小于:
<
if (( a > b )); then echo "a > b"; fi
- 大于:
循环控制
1. for
循环
语法:
for var in item1 item2 ... itemN
docommand1command2...
done
示例:
for i in 1 2 3 4 5
doecho "$i"
done
: '
1
2
3
4
5
'
字符串分词:
for word in This is a string
doecho $word
done
2. while
循环
语法:
while condition
docommand
done
示例:
num_1=1
while (( num_1 <= 10 ))
doecho "$num_1"let "num_1++"
doneecho "$num_1": '
1
2
3
4
5
6
7
8
9
10
11
'
读取输入:
echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的博主: '
while read nickName
doecho "是的!$nickName 是一个好博主"
done
3. 无限循环
语法:
while :
docommand
done
或:
while true
docommand
done
4. until
循环
于
while
里面的条件相反,是达到该条件才停止循环,比较少用
语法:
until condition
docommand
done
示例:
a=0
until [ ! $a -lt 10 ]
doecho $aa=$((a + 1))
done
条件匹配
case ... esac
语句
语法:
case value in
pattern1)command1;;
pattern2)command2;;
*)default_command;;
esac
示例:
num=4
num_1=1
num_2=2
num_3=3case $num in$num_1) printf "num==num_1";;$num_2) printf "num==num_2";;$num_3) printf "num==num_3";;*) printf "other case";;
esac# printf: other case
跳出与继续循环
break
- 跳出所有循环:
while :
doread -p "输入 1 到 5 之间的数字:" numcase $num in1|2|3|4|5) echo "你输入的数字为 $num!" ;;*) echo "游戏结束"; break ;;esac
done
continue
- 跳过当前循环的剩余部分,直接进入下一次循环:
while :
doread -p "输入 1 到 5 之间的数字:" numcase $num in1|2|3|4|5) echo "你输入的数字为 $num!" ;;*) echo "输入错误,重新开始"; continue ;;esac
done