Bash遍历多个目录

时间:2020-08-07 11:15:04

标签: arrays bash for-loop

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

我有一个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

谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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