在shell脚本中,for循环有很多种,今天就对以下几种做一个简单的总结。
1、循环数字
#!/bin/bash for((i=1;i<=10;i++)); do echo $(expr $i \* 3 + 1); done
#!/bin/bash for i in $(seq 1 10) do echo $(expr $i \* 3 + 1); done
#!/bin/bash for i in {1..10} do echo $(expr $i \* 3 + 1); done
#!/bin/bash awk 'BEGIN{for(i=1; i<=10; i++) print i}'
结果:
4 7 10 13 16 19 22 25 28 31
2、循环字符串
#!/bin/bash for i in `ls`; do echo $i is file name\! ; done
结果(输出当前文件名):
for.sh
#!/bin/bash for i in $* ; do echo $i is input chart\! ; done
结果(输出当前所有入参):
192:shell-home xxx$ sh for.sh param1 param2 param3 param1 is input chart! param2 is input chart! param3 is input chart!
#!/bin/bash for i in f1 f2 f3 ; do echo $i is appoint ; done
结果(循环空格隔开的字符list):
192:shell-home xxx$ sh for.sh f1 is appoint f2 is appoint f3 is appoint
#!/bin/bash list="rootfs usr data data2" for i in $list; do echo $i is appoint ; done
结果(循环list):
192:shell-home xxx$ sh for.sh rootfs is appoint usr is appoint data is appoint data2 is appoint
3、路径查找
#!/bin/bash for file in /Volumes/work/*; do echo $file is file path \! ; done
结果(循环查找当前目录):
192:shell-home xxx$ sh for.sh /Volumes/work/BAK_0_MEDIA is file path ! /Volumes/work/BAK_0_TEXT is file path ! /Volumes/work/apache-maven-3.5.3 is file path ! /Volumes/work/apache-tomcat-9.0.8 is file path ! /Volumes/work/chromedriver is file path ! /Volumes/work/git-repository is file path ! /Volumes/work/intellij-setting-files is file path ! /Volumes/work/justfortest is file path ! /Volumes/work/mavenRepository is file path ! /Volumes/work/pathfordownload is file path ! /Volumes/work/selenium-server-standalone-3.0.0.jar is file path ! /Volumes/work/shell-home is file path !
#!/bin/bash for file in $(ls /Volumes/work) do echo $file is file path \! ; done
结果(循环取出ls的结果):
192:shell-home xxx$ sh for.sh BAK_0_MEDIA is file path ! BAK_0_TEXT is file path ! apache-maven-3.5.3 is file path ! apache-tomcat-9.0.8 is file path ! chromedriver is file path ! git-repository is file path ! intellij-setting-files is file path ! justfortest is file path ! mavenRepository is file path ! pathfordownload is file path ! selenium-server-standalone-3.0.0.jar is file path ! shell-home is file path !
Stay hungry,stay foolish !
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?