bash - 如何在 Bash 中运行多个 inotifywait 循环?

标签 bash

我有一个脚本作为监听文件的守护进程运行:

#!/bin/bash
echo '1'
while inotifywait -e close_write /home/homeassistant/.homeassistant/automations.yaml
do
    echo 'automations'
    curl -X POST -H "x-ha-access: pass" -H "Content-Type: application/json" http://hassbian.local:8123/api/services/automation/reload
done;

我想听几个文件,并尝试添加两个循环:

while inotifywait -e close_write /home/homeassistant/.homeassistant/groups.yaml
do
    echo 'gropus'
    curl -X POST -H "x-ha-access: pass" -H "Content-Type: application/json" http://hassbian.local:8123/api/services/group/reload
done;

while inotifywait -e close_write /home/homeassistant/.homeassistant/core.yaml
do
    echo 'core'
    curl -X POST -H "x-ha-access: pass" -H "Content-Type: application/json" http://hassbian.local:8123/api/services/homeassistant/reload_core_config
done;

我意识到第一个循环永远不会关闭,所以其他循环永远不会开始,但不确定我应该如何解决这个问题。

最佳答案

您需要在后台进程中运行第一个循环,这样它就不会阻塞您的脚本。您可能希望在后台运行每个 循环以实现对称,然后在脚本末尾等待它们。

while inotifywait -e close_write /home/homeassistant/.homeassistant/groups.yaml
do
    echo 'gropus'
    curl -X POST -H "x-ha-access: pass" -H "Content-Type: application/json" http://hassbian.local:8123/api/services/group/reload
done &

while inotifywait -e close_write /home/homeassistant/.homeassistant/core.yaml
do
    echo 'core'
    curl -X POST -H "x-ha-access: pass" -H "Content-Type: application/json" http://hassbian.local:8123/api/services/homeassistant/reload_core_config
done &

wait

但是,您可以在监控模式下运行 inotifywait 并监控多个文件,将其输出管道化到一个循环中。 (警告:与任何面向行的输出格式一样,这无法处理包含换行符的文件名。请参阅 --format--csv 选项来处理包含空格的文件名。 )

files=(
  /home/homeassistant/.homeassistant/groups.yaml
  /home/homeassistant/.homeassistant/core.yaml
)

take_action () {
    echo "$1"
    curl -X POST "x-ha-access: pass" -H "Content-Type: application/json" \
      http://hassbian.local:8123/api/services/"$2"
}

inotifywait -m -e close_write "${files[@]}" |
  while IFS= read -r fname _; do
    case $fname in
      */groups.yaml) take_action "groups" "group/reload" ;;
      */core.yaml)   take_action "core" "homeassistant/reload_core_config" ;;
    sac
  done

关于bash - 如何在 Bash 中运行多个 inotifywait 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292040/

相关文章:

linux - 使用 bash 在 Linux 中查找拥有文件夹中文件的所有用户

bash - :'END'在bash中如何工作以创建多行注释 block ?

bash - 连接行,对记录数取模

linux - 关于 Makefile 的 bash shell

python - 在python脚本中获取路径

macos - RAM 中的音频文件并播放 - Bash 4.3.42

bash - 当文件已重定向到标准输入时读取用户输入的标准输入

linux - 使用 WGET 从网站/目录下载所有 .tar.gz 文件

string - 想要更改前缀字符,然后在更改的字符串中添加后缀字符

arrays - 在 Bash 中添加和列出数组元素