ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## while 循环 语法: ``` while condition; do commands done or while condition; do commands done ``` 示例: ``` number=0 while [ "$number" -lt 10 ]; do echo "Number = $number" number=$((number + 1)) done ``` ## until 循环 只要不符合判断条件(判断条件失败) 语法: ``` until condition; do commands done ``` 示例 ``` #!/bin/bash number=0 until [ "$number" -ge 10 ]; do echo "Number = $number" number=$((number + 1)) done ``` ## for...in 循环 语法 ``` for variable in list do commands done ``` 实例1:数组循环 ``` #!/bin/bash f=(1 2 3) # 追加数组 f+=(4 5) for i in ${f[@]};do echo $i done ``` 示例2 ``` #!/bin/bash for i in word1 word2 word3; do echo $i done ``` 示例3: 遍历当前目录下的文件 ``` #! /bin/bash for i in *.dmg do file $i done ``` 示例4:列表也可以通过子命令产生 ``` #!/bin/bash count=0 for i in $(cat ~/.bash_profile); do count=$((count + 1)) echo "Word $count ($i) contains $(echo -n $i | wc -c) characters" done ``` ## for 循环 语法: ``` for (( expression1; expression2; expression3 )); do commands done ``` 示例 ``` for (( i=0; i<5; i=i+1 )); do echo $i done ``` ## break,continue ``` #!/bin/bash for number in 1 2 3 4 5 6 do echo "number is $number" if [ "$number" = "3" ]; then break fi done ```