linux控制流程,Linux - Bash - 流程控制
sh的流程控制不可為空,不能什么都不能做,不能像php這樣:
if (isset($_GET["q"])) {
search(q);
}
else {
// 不做任何事情
}
在sh/bash里可不能這么寫,如果else分支沒有語句執(zhí)行,就不要寫這個(gè)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
這個(gè)bash命令是判斷mysql是否運(yùn)行,grep 有一個(gè),如果運(yùn)行一個(gè)Mysql就是2,就大于1了。
$() 是調(diào)用 命令 和 `` 相等。
這里的[]是用于test,不是用于數(shù)值計(jì)算, 不能用(( ))代替。
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 循環(huán)
for 循環(huán)的一般格式:
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循環(huán)用于不斷執(zhí)行一系列命令,也用于從輸入文件中讀取數(shù)據(jù);命令通常為測(cè)試條件。其格式為:
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--
簡(jiǎn)寫形式 let no+=10,let no-=20,分別等同于 let no=no+10,let no=no-20。
let "a++"
和
let a++
都沒有什么區(qū)別樣。
echo "請(qǐng)輸入(按下)"
echo -n '輸入你最喜歡的網(wǎng)站名字:'
while read FILM ; do
echo "是的, $FILM 是很好的網(wǎng)站"
done
while無限循環(huán)
while :
do
command
done
或者:
while true
do
command
done
經(jīng)驗(yàn):
1.我們?cè)跅l件的時(shí)候如果取反,可以加!:
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
總結(jié)
以上是生活随笔為你收集整理的linux控制流程,Linux - Bash - 流程控制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 执行计划中cpu耗时_面试被问怎么排查遇
- 下一篇: 文件名重定向到txt中Linux,Lin