linux控制流程,Linux - Bash - 流程控制
sh的流程控制不可為空,不能什么都不能做,不能像php這樣:
if (isset($_GET["q"])) {
search(q);
}
else {
// 不做任何事情
}
在sh/bash里可不能這么寫,如果else分支沒有語句執行,就不要寫這個else。
if else
if
if語句語法格式:
if condition
then
command1
command2
...
commandN
fi
寫成一行(適用于終端命令提示符):
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
if [ $(ps aux | grep -c "mysql") -gt 1 ]
then
echo "true"
else
echo "false"
fi
這個bash命令是判斷mysql是否運行,grep 有一個,如果運行一個Mysql就是2,就大于1了。
$() 是調用 命令 和 `` 相等。
這里的[]是用于test,不是用于數值計算, 不能用(( ))代替。
if else
if condition
then
command1
command2
...
commandN
else
command
fi
if elif else
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
for 循環
for 循環的一般格式:
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
寫成一行:
for var in item1 item2 ... itemN; do command1; command2… done;
案例:
for var in 1 2 3 4 5
do
echo "this value is: $var"
done
輸出字符串:
for str in 'This is a string'
do
echo $str
done
while 語句
while循環用于不斷執行一系列命令,也用于從輸入文件中讀取數據;命令通常為測試條件。其格式為:
while condition
do
command
done
案例:
下面三種方式是一樣額。
int=1
while (( $int <= 5 ))
do
echo $int
let "int++"
done
int=1
while [ $int -le 5 ]
do
echo $int
let "int++"
done
int=1
while test $int -le 5
do
echo $int
let "int++"
done
let:的解釋 let
自加操作:let no++
自減操作:let no--
簡寫形式 let no+=10,let no-=20,分別等同于 let no=no+10,let no=no-20。
let "a++"
和
let a++
都沒有什么區別樣。
echo "請輸入(按下)"
echo -n '輸入你最喜歡的網站名字:'
while read FILM ; do
echo "是的, $FILM 是很好的網站"
done
while無限循環
while :
do
command
done
或者:
while true
do
command
done
經驗:
1.我們在條件的時候如果取反,可以加!:
MAX_NO=0
echo -n "Enter Number between(5 to 9):"
read MAX_NO
echo $MAX_NO
if ![ $MAX_NO -ge 5 -a $MAX_NO -le 9]; then
echo "WTF...I ask you to enter the number between 5 and 9, try again"
exit 1
fi
總結
以上是生活随笔為你收集整理的linux控制流程,Linux - Bash - 流程控制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 执行计划中cpu耗时_面试被问怎么排查遇
- 下一篇: antd table设置表格一个单元格的