Shell编程 - 循环篇

1. for循环

  • 格式:
for 变量名 in 取值列表; do
    命令
done
  • 示例:
#!/bin/bash
for i in {1..3}; do
    echo $i
done
# bash test.sh
1
2
3

for的语法也可以这么写:
#!/bin/bash
for i in "$@"; {    # $@是将位置参数作为单个来处理
    echo $i
}
# bash test.sh 1 2 3
1
2
3

2. while语句

  • 格式:
while 条件表达式; do
    命令
done
  • 示例1:
#!/bin/bash
N=0
while [ $N -lt 5 ]; do
    let N++
    echo $N
done
# bash test.sh
1
2
3
4
5

当条件表达式为false时,终止循环。

  • 示例2:条件表达式为true,将会产生死循环
1. 直接写正确的表达式
#!/bin/bash
while [ 1 -eq 1 ]; do
    echo "yes"
done

2. 也可以条件表达式直接用true#!/bin/bash
while true; do
  echo "yes"
done

3. 还可以条件表达式用冒号,冒号在Shell中的意思是不做任何操作。但状态是0,因此为true#!/bin/bash
while :; do
    echo "yes"
done
  • 示例3:逐行处理文本
    • 文本内容:
      # cat a.txt
      a b c
      1 2 3
      x y z
      
    • 要想使用while循环逐行读取a.txt文件,有三种方式:
      • 方式1:⭐
         #!/bin/bash
         cat ./a.txt | while read LINE; do
             echo $LINE
         done
        
      • 方式2:⭐⭐⭐
        #!/bin/bash
        while read LINE; do
            echo $LINE
        done < ./a.txt
        
      • 方式3: ⭐
          #!/bin/bash
          exec < ./a.txt  # 读取文件作为标准输出
          while read LINE; do
              echo $LINE
          done
        

案例2. 通过while read方式,统计ip.txt文件,次数大于5,ping下.

  • ip.txt:
 10.0.0.61 5
 10.0.0.7  6
 10.0.0.8  8
 baidu.com  10
 jd.com  5
#1.vars
 src_file=./ip.txt
#2.while读取与判断
while read ip count
 do
    #ip=`echo $line+awk取列`
    if [ $count -ge  5 ];then
       ping -c 1  $ip  &>/dev/null
       if [ $? -eq 0 ];then
          greenecho "$ip 可以访问"
       else
          redecho "$ip 不可以访问"
       fi
    fi
 done <$src_file

3. break和continue语句

break是终止循环。
continue是跳出当前循环。

  • 示例1:在死循环中,满足条件终止循环
#!/bin/bash
N=0
while true; do
    let N++
    if [ $N -eq 5 ]; then
        break
    fi
    echo $N
done
# bash test.sh
1
2
3
4

里面用了if判断,并用了break语句,它是跳出循环。与其关联的还有一个continue语句,它是跳出本次循环。

  • 示例2:举例子说明continue用法
#!/bin/bash
N=0
while [ $N -lt 5 ]; do
    let N++
    if [ $N -eq 3 ]; then
        continue
    fi
    echo $N
done
# bash test.sh
1
2
4
5

当变量N等于3时,continue跳过了当前循环,没有执行下面的echo。
注意:continue与break语句只能循环语句中使用。

posted @   kyle_7Qc  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示