300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > shell while 结束循环_Shell脚本编程2 for循环/while循环

shell while 结束循环_Shell脚本编程2 for循环/while循环

时间:2019-11-17 01:59:55

相关推荐

shell while 结束循环_Shell脚本编程2 for循环/while循环

For循环

和java中的for是一样的都是循环

与其他编程语言类似,Shell支持for循环。

for循环的作用:依次遍历列表中的值,直到终止或遍历完成

for循环一般格式为:

for var in item1 item2 ... itemNdo command1 command2 ... commandNdone

当变量值在列表里,for循环即执行一次所有命令,使用变量名获取列表中的当前取值。命令可为任何有效的shell命令和语句。in列表可以包含字符串和文件名。

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

for loop in 1 2 3 4 5do echo "The value is: $loop"done

输出结果:

The value is: 1The value is: 2The value is: 3The value is: 4The value is: 5

for循环

除此之外,还有以下几种格式:

for NUM in 1 2 3for NUM in {1..3}for NUM in {a..f}for NUM in `seq 1 3 `for NUM in `seq 1 2 5` //可以设定步长;2就是步长,输出为 1 3 5注意:{1..5}是1到5,`seq 1 5 `也是1到5,但seq可以设定步长

还可以是计算的方式(和Java语言类似)

for((A=1;A<=10;A++))

do

done

Example:

顺序输出字符串中的字符:

for str in 'This is a string'do echo $strdone

输出结果:

This is a string

while 语句

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:

while conditiondo commanddone

以下是一个基本的while循环,测试条件是:如果int小于等于5,那么条件返回真。int从0开始,每次循环处理时,int加1。运行上述脚本,返回数字1到5,然后终止。

#!/bin/bashint=1while(( $int<=5 ))do echo $int let "int++"done

运行脚本,输出:

12345

While读取文件

读取文件给 while 循环

方式一:

exec

方式二:

cat [FILE] |while read line docmd done

方式三:

while read line docmd done

[FILE] 替换成文件路径

举例:

ip.txt内容如下:

10.1.1.11 root 12310.1.1.22 root 11110.1.1.33 root 12345610.1.1.44 root 54321

写法1:

cat ip.txt | while read ip user passdo echo "$ip--$user--$pass"done

写法2:

while read ip user passdo echo "$ip--$user--$pass"done < ip.txt

使用IFS作为分隔符读文件

说明:默认情况下IFS是空格,如果需要使用其它的需要重新赋值

IFS=:

例如:

# cat test

chen:222:gogojie:333:hehe

# cat test.sh

#!/bin/bashIFS=:cat test | while read a1 a2 a3do echo "$a1--$a2--$a3"done

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。