bash 进行for循环

发布时间:2026/6/27 12:25:02
bash 进行for循环 这是 Shell 中很常见的需求不要定义PATH1、PATH2、PATH3再一个个处理而是把所有路径放到一个列表中再用for循环。方法一使用数组推荐bash#!/bin/bashdirs(/tmp/log/home/user/data/opt/test)fordirin${dirs[]};doechoProcessing$dirif[-d$dir];thenls$direlseecho$dirdoes not existfidone优点路径中可以包含空格易于维护添加路径只需增加一行方法二直接在 for 中写路径如果路径数量不多fordirin\/tmp/log\/home/user/data\/opt/testdoecho$dirdone方法三变量保存多个路径DIRS/tmp/log /home/user/data /opt/testfordirin$DIRSdoecho$dirdone注意这种方法不能处理包含空格的路径例如/home/user/my dir会被拆成两个字符串。方法四从文件读取例如dirs.txt/tmp/log /home/user/data /opt/test脚本whileIFSread-rdirdoecho$dirdonedirs.txt适合路径很多的时候。如果你的环境是 tcsh由于你之前提到经常使用tcsh写法有所不同set dirs ( \ /tmp/log \ /home/user/data \ /opt/test \ ) foreach dir ($dirs) echo $dir if ( -d $dir ) then ls $dir else echo $dir does not exist endif end推荐bash使用数组方法一。tcsh使用set dirs (...)foreach。这两种方式都是最清晰、最容易维护的写法。如果每个目录都有一个对应的文件名最好的做法是把它们成对保存而不是分别保存两个列表否则容易对应错。方法一两个数组bash推荐#!/bin/bashdirs(/tmp/log1/tmp/log2/tmp/log3)files(run.logerror.logdebug.log)for((i0;i${#dirs[]};i));dodir${dirs[i]}file${files[i]}echoProcessing:$dir/$fileif[-f$dir/$file];thencat$dir/$fileelseecho$dir/$filedoes not existfidone输出类似Processing: /tmp/log1/run.log Processing: /tmp/log2/error.log Processing: /tmp/log3/debug.log方法二把目录和文件名写在一起更推荐如果它们是一一对应的可以直接保存完整路径paths(/tmp/log1/run.log/tmp/log2/error.log/tmp/log3/debug.log)forpathin${paths[]};doecho$pathif[-f$path];thencat$pathfidone这是最简单、最不容易出错的方式。方法三关联关系键值对如果一个目录始终对应一个文件可以用关联数组需要 Bash 4declare-Alogs logs[/tmp/log1]run.loglogs[/tmp/log2]error.loglogs[/tmp/log3]debug.logfordirin${!logs[]};dofile${logs[$dir]}echo$dir/$filedone如果你使用的是 tcshtcsh没有数组索引和关联数组那么方便通常用两个列表set dirs ( /tmp/log1 /tmp/log2 /tmp/log3 ) set files ( run.log error.log debug.log ) i 1 while ( $i $#dirs ) echo $dirs[$i]/$files[$i] i end推荐选择根据你之前的问题你主要写的是bash脚本因此建议如果目录和文件名固定对应直接保存完整路径方法二最简洁。如果目录和文件名后续可能分别使用使用两个数组通过相同索引对应方法一可维护性最好。