首页 > 解决方案 > Bash 循环遍历多个目录

问题描述

我不知道是否达到了这个话题,或者机器人找不到任何相关的东西。

我有一个 bash 脚本,我想在多个目录中执行 for 循环,并提到我只想在日志文件中输出,*.txt/files但循环不要在子目录中进行。

我的愿望是使用变量中的目录。我正在使用一个数组,我在其中编写了我搜索它们的目录。运行脚本时,输出是数组中的内容,而不是目录中的内容...

这就是我的代码现在的样子,我该怎么办?:

#!/bin/bash

l=/home/Files/Test1/
j=/home/Files/Test2/
k=/home/Files/Test3/

arr=("$l" "$j" "$k")

for i in "${arr[*]}"
do
  echo "$i"  >> test
done

感谢您的任何帮助!

标签: arraysbashfor-loop

解决方案


只是find实际的文件。

find "${arr[@]}" -maxdepth 1 -type f >> test

可以依赖 shell 文件名扩展:

for dir in "${arr[@]}" # properly handle spaces in array values
do
      for file in "$dir"/*; do
          # check for empty dir
          if [ -f "$file" ]; then
              # Use printf, in case file is named ex. `-e`
              printf "%s\n" "$file"
          fi
      done
# don't reopen the file on each loop, just open it once
done >> test

但还有很多,仅find此而已。


推荐阅读