【问题标题】:Bash loop through multiple directoriesBash 循环遍历多个目录
【发布时间】:2020-08-07 11:15:04
【问题描述】:

我不知道这个话题是否已经达到或没有机器人找不到任何相关的东西。

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

感谢您的帮助!

【问题讨论】:

  • I want to do a for loop through multiple directories 你这么说,但我认为你的意思是要循环遍历多个目录中的文件,而不是目录。
  • 是的,很抱歉造成混淆..

标签: arrays bash for-loop


【解决方案1】:

只是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 即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2013-09-20
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多