shell--分支与循环结构
if 条件语句
if [[ $1 = start ]];then echo start app elif [[ $1 = stop ]];then echo stop app
elif [[ $1 = ... ]];then
.... else echo Please input command! fi
case条件语句
#/bin/bash read -p "Please input number: " option case $option in "1") echo "the number you input is 1" ;; "2") echo "the number you input is 2" ;; [3-9]) echo "the number you input is $option" ;; *) echo ” the number must less 9" ;; esac
其中条件部分可以写成 "1|99",[3-9]等
while循环语句
#/bin/bash
sum=0
i=0
while ((i<=10))
do
((sum=sum+i))
((i++))
done
echo $sum
一般用while做死循环的情况较多
#/bin/bash while true do uptime sleep 5 done
还有一种用于一行一行的读取输入文件
lsof -i:80|awk '{print $2}'|while read line;do [ $line != PID ]&& kill -9 $line;done
for
#/bin/bash # for i in `ls /usr/local/src` for i in {sleep,dinner,sport} do echo $i done
还有一种c语言风格的,
##计算0加到100
#/bin/bash sum=0 for ((i=0;i<=100;i++)) do sum=$(($sum+$i)) done echo $sum
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步