shell基础(八)-循环语句

   国庆事后;感受有点慵懒些了;接着上篇;咱们继续来学习循环语句。python

    一. for循环编程

        与其余编程语言相似,Shell支持for循环。bash

for循环通常格式为:
for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done

   列表是一组值(数字、字符串等)组成的序列,每一个值经过空格分隔。每循环一次,就将列表中的下一个值赋给变量编程语言

   例如,顺序输出当前列表中的数字学习

for01.sh
$ cat for01.sh 
#!/bin/sh
for i in 1 2 3 4 5
do
 echo "this is $i"
done
$ ./for01.sh 
this is 1
this is 2
this is 3
this is 4
this is 5

 固然也能够向其余语言那样for ((i=1;i++<5));可是是要双括号;这个是不同凡响。测试

#!/bin/sh
for ((i=1;i<=5;i++))
do
 echo "this is $i"
done

 【注意】in 列表是可选的,若是不用它,for 循环使用命令行的位置参数。以下:ui

$ cat for01.sh 
#!/bin/sh
for i
do
 echo "this is $i"
done
$ ./for01.sh 1 2 3 4 5  
this is 1
this is 2
this is 3
this is 4
this is 5

 【note】对于列表;像上面同样;其实命令ls当前目录下的全部文件就是一个列表this


 

   二.while 循环命令行

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令一般为测试条件blog

#其格式为:
while command
do
   Statement(s) to be executed if command is true
done

 命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。
以for循环的例子。

$ cat while01.sh 
#!/bin/sh
i=0
while [ $i -lt 5 ]
do
 let "i++"
 echo "this is $i"
done
$ ./while01.sh 
this is 1
this is 2
this is 3
this is 4
this is 5

 其实while循环用的最可能是用来读文件。

#!/bin/bash
count=1    
cat test | while read line        #cat 命令的输出做为read命令的输入,read读到的值放在line中
do
   echo "Line $count:$line"
   count=$[ $count + 1 ]          
done
或者以下
#!/bin/sh
count=1
while read line
do 
  echo "Line $count:$line"
   count=$[ $count + 1 ]  
done < test

 【注意】固然你用awk的话;那是至关简单;awk '{print "Line " NR " : " $0}' test
输出时要去除冒号域分隔符,可以使用变量IFS。在改变它以前保存IFS的当前设置。而后在脚本执行完后恢复此设置。使用IFS能够将域分隔符改成冒号而不是空格或tab键

例如文件worker.txt
Louise Conrad:Accounts:ACC8987
Peter Jamas:Payroll:PR489
Fred Terms:Customer:CUS012
James Lenod:Accounts:ACC887
Frank Pavely:Payroll:PR489
while02.sh以下:
#!/bin/sh
#author: li0924
#SAVEIFS=$IFS
IFS=:
while read name dept id
 do
  echo -e "$name\t$dept\t$id"
 done < worker.txt
#IFS=$SAVEIFS

 

   三.until循环

until 循环执行一系列命令直至条件为 true 时中止。until 循环与 while 循环在处理方式上恰好相反

until 循环格式为: 
until command
do
   Statement(s) to be executed until command is true
done

 command 通常为条件表达式,若是返回值为 false,则继续执行循环体内的语句,不然跳出循环

$ cat until01.sh 
#!/bin/sh
i=0
until [ $i -gt 5 ]
do
 let "i++"
 echo "this is $i"
done

 通常while循环优于until循环,但在某些时候,也只是极少数状况下,until 循环更加有用。详细介绍until就没必要要了


 

   四. break和continue命令

1. break命令
break命令容许跳出全部循环(终止执行后面的全部循环)
2.continue命令
continue命令与break命令相似,只有一点差异,它不会跳出全部循环,仅仅跳出当前循环。

break01.sh
#!/bin/sh
for ((i=1;i<=5;i++))
do
 if [ $i == 2 ];then
 break
 else
 echo "this is $i"
 fi
done

 至于continue命令演示;你就把break替换下;执行看下效果就好了。不解释。

相关文章
相关标签/搜索