专业的编程技术博客社区

网站首页 > 博客文章 正文

Shell脚本编程2 for循环/while循环

baijin 2024-09-04 02:13:47 博客文章 6 ℃ 0 评论

For循环

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

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

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

for循环一般格式为:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

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

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

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

输出结果:

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


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

for NUM in 1 2 3 
for 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 $str
done

输出结果:

This is a string


while 语句

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

while condition
do
    command
done

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

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

运行脚本,输出:

1
2
3
4
5

While读取文件

读取文件给 while 循环
方式一:

exec <[FILE]
while read line 
do 
    cmd 
done 

方式二:

cat [FILE] |while read line 
do 
    cmd 
done 

方式三:

while read line 
do 
    cmd 
done <[FILE]

[FILE] 替换成文件路径

举例:

ip.txt内容如下:

10.1.1.11 root 123
10.1.1.22 root 111
10.1.1.33 root 123456
10.1.1.44 root 54321

写法1:

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

写法2:

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

使用IFS作为分隔符读文件

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

IFS=:

例如:

# cat test
chen:222:gogo
jie:333:hehe
# cat test.sh
#!/bin/bash
IFS=:
cat test | while read a1 a2 a3
do
    echo "$a1--$a2--$a3"
done

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表