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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值