我正在编写一个 bash 脚本,用于inotifywait监视目录并在检测到更改时启动操作。就像是:
inotifywait -m ... | while read f; do something; done
Run Code Online (Sandbox Code Playgroud)
由于inotifywait不会自行终止,因此该脚本不会停止。
所以我的计划是获取 inotifywait 进程的 PID,将其保存到一个文件中,然后让不同的进程将其杀死,例如:
inotifywait -m ... | { echo ??PID?? > pid-file; while ... }
Run Code Online (Sandbox Code Playgroud)
但我不知道如何获得PID。有没有简单的方法来实现这一目标?另一种方法是将 shell 脚本的 PID 保存$$到文件中并终止整个 shell 脚本,但我想在 while 循环后进行一些清理。
我试过使用coproc,我认为它会起作用,但它似乎比必要的更复杂。
在一个管道,所有进程都开始同时,有没有一个是早比别人。
你可以这样做:
(echo "$BASHPID" > pid-file; exec inotifywait -m ...) | while IFS= read -r...
Run Code Online (Sandbox Code Playgroud)
或者便携:
sh -c 'echo "$$" > pid-file; exec inotifywait -m ...' | while IFS= read -r...
Run Code Online (Sandbox Code Playgroud)
另请注意,当运行while循环的子shell终止时,inotifywait它将在下次向标准输出写入内容时自动终止。