随笔 - 361,  文章 - 0,  评论 - 62,  阅读 - 160万

  在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 !
复制代码
posted on   kosamino  阅读(45460)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示