2017-05-31 89 views
2

我跑作为守护听文件的脚本:如何在Bash中运行多个inotifywait循环?

#!/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; 

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

+0

?你是否期望文件重新打开并关闭多次,每次关闭时都调用'curl'? – chepner

回答

3

您需要在后台进程中运行第一个循环,以便它不会阻止脚本。您可能需要在背景中运行每个循环以获得对称性,然后在脚本结尾处等待它们。

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