【Linux Shell】shell命令读书笔记---第六章:使用循环进行流控制

来源:互联网 发布:java交换两个字符变量 编辑:程序博客网 时间:2024/06/04 18:53

6.1 for 循环

语法结构

for       in

do

done

例子:

[root@dev34 daodao]# vim fruit.sh#!/bin/bashfor fruit in apple orange peardo  echo "I really like ${fruit}s"doneecho "Let's make a salad!"[root@dev34 daodao]# sh fruit.shI really like applesI really like orangesI really like pearsLet's make a salad!


for循环的使用机制,在已经要对一个元素集合执行相同操作,而不是重复执行某个操作直到满足某个条件时,使用for 循环最合适。如果需要终止循环,for不是很适合。

[root@dev34 daodao]# cat fruit-var.sh#!/bin/bashfruits="apple orange pear"for fruit in $fruitsdo  echo "I really like ${fruit}s"doneecho "Let's make a salad!"[root@dev34 daodao]# sh fruit-var.shI really like applesI really like orangesI really like pearsLet's make a salad!
[root@dev34 daodao]# cat fruit-read.sh #!/bin/bashecho -en "Please tell me some of your favorite fruits: "read fruitsfor fruit in $fruitsdo  echo "I really like ${fruit}s"doneecho "Let's make a salad!"[root@dev34 daodao]# sh fruit-read.sh  Please tell me some of your favorite fruits: kiwi banana grape appleI really like kiwisI really like bananasI really like grapesI really like applesLet's make a salad!
[root@dev34 daodao]# cat fruit-function.sh#!/bin/bashdo_i_like(){  for fruit  do    echo I really like $fruit  done}do_i_like apples bananas orangesdo_i_like satsumas apricots cherriesecho "Let's make a salad!"[root@dev34 daodao]# sh fruit-function.sh I really like applesI really like bananasI really like orangesI really like satsumasI really like apricotsI really like cherriesLet's make a salad!

这些脚本都需要手工输入很麻烦,主要是用seq命令,可以实现循环操作:

比如监视网络中的计算机哪些响应ping命令,而哪些不响应:


 

原创粉丝点击