`
xiaoer_1982
  • 浏览: 1819992 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

BASH学习笔记5——控制结构

阅读更多

1.if语句
if...then....elif....then....else.....fi
在命令行上可以用test来测试表达式真假,man test可以看到条件测试的一些用法,比如-lt,-a,-o等,若一个命令作为条件则注意要在后边加上“;”,分号表示一行可以写多个语句。
注意下边的写法,这也是一种化简的if手段
[ ! -d ${MntDir} ] && mkdir ${MntDir}
The control operators ‘&&’ and ‘||’ denote and lists and or lists, respectively. An and
list has the form
command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero.
An or list has the form
command1 || command2
command2 is executed if, and only if, command1 returns a non-zero exit status.
这也就是说我们可以用与、或代替条件判断分支语句:
判断条件成功则执行--用“与”。
判断条件不成功则执行--用“或”。
注意其与if里面的条件判断是不同的,这里0代表程序成立,其他代表成立。

2. case语句
case ... in
A)
;;
B)
;;
*)
esac
其中条件中可以使用|来同时匹配多个条件

3.for循环
for name in ....
do
done
name会从列表中一个个被赋值,若没有列表则会使用位置参数进行循环。
列表可以是一个命令的执行结果或一个文件

4.until循环
until ...
do
done
特点是至少执行了一次。
5.while循环
while ...
do
done
数据读入要在done后边写入,这样才能读完后就能读下一个(感觉怎么这么奇怪。。。)
例如:
while read LINE
do
echo $LINE
done <names.txt

6.break和continue

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics