如何编写 while 循环以便使用 bash 完成以下任务?

How to write while loop so that the following task can be accomplished using bash?

我正在编写一个脚本,如果文件夹发生变化,假设文件从文件夹中删除,那么脚本应该执行,并且该脚本正在检查多个文件夹。以下是我为执行相同操作而编写的代码,但并未针对所有语句执行,只有第一条语句有效。 有人可以看看它并指导如何完成这项任务吗?欢迎提出任何建议。谢谢。

folder2=/script/automation/folder2
folder1=/script/automation/folder1
folder3=/script/automation/folder3


# While statement
/usr/local/bin/inotifywait -mqr -e delete $folder2 | while read line
do
./script/automation/run2/script2.sh >> /output.txt
done

/usr/local/bin/inotifywait -mqr -e delete $folder1 | while read line
do
./script/automation/run1/script1.sh >> /output.txt
done

/usr/local/bin/inotifywait -mqr -e delete $folder3 | while read line
do
./script/automation/run3/script3.sh >> /output.txt
done

第一个 while read 永远不会完成。这就是为什么第二个和第三个循环永远不会 运行 的原因。您必须 运行 并行循环,这意味着,您必须使用 & 将它们置于后台,并且您必须等待后台任务。

如果你做三次同样的事情,最好为这个工作写一个函数。 Don't repeat yourself.

命令exec > output.txt 将所有输出重定向到一个文件。所以你不需要重定向每一个命令。

尝试这样的事情。

#! /bin/bash

base=script/automation

run ()
{
  local folder=
  local script=

  /usr/local/bin/inotifywait -mqr -e delete "$base/$folder" |
    while read line; do
      "$base/$script"
    done
}

exec > output.txt

for n in 1 2 3; do
  run "folder$n" "run$n/script$n.sh" &
done

wait