【问题标题】:inotifywait not performing the while loop in bash scriptinotifywait 未在 bash 脚本中执行 while 循环
【发布时间】:2019-04-23 14:03:17
【问题描述】:

我想在我的 Docker 容器中的目录上放置一个文件观察器。我正在使用entrypoint.sh 脚本来设置放置文件观察器的脚本。设置是这样的:

#!/bin/sh

# Trigger the script with the file watcher in the background
./bin/watcher.sh &

watcher.sh 脚本包含inotifywait 命令:

#!/bin/sh

inotifywait \
    --event create --event delete \
    --event modify --event move \
    --format "%e %w%f" \
    --monitor --outfile '/var/log/inotifywait.log' \
    --syslog --quiet --recursive \
    /etc/haproxy |
while read CHANGED;
do
    echo "$CHANGED"
    haproxy -W -db -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid) &
done

但是,虽然当我检查top 时会列出观察程序,并且它会报告定义的日志文件中的更改,但循环永远不会触发。我试过用简单的方法调试循环:

    touch /var/log/special.log
    echo "${CHANGED}" >> /var/log/special.log

但是文件永远不会被创建,并且没有任何内容被回显。在 bash 脚本中使用 inotifywait 与循环的正确方法是什么?

【问题讨论】:

    标签: linux bash sh alpine inotify


    【解决方案1】:

    您使用--outfile 选项将输出显式发送到文件而不是stdout。从来没有向stdout 写入任何内容,因此while 循环中的read 语句从不读取任何数据。

    你可能想要:

    inotifywait \
        --event create --event delete \
        --event modify --event move \
        --format "%e %w%f" \
        --monitor \
        --syslog --quiet --recursive \
        /etc/haproxy |
    while read CHANGED;
    do
        echo "$CHANGED"
        haproxy -W -db -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid) &
    done
    

    【讨论】:

    • 当我删除 --outfile 时仍然没有任何反应。奇怪的是,当我删除 outfile 并尝试触发 inotifywait 时,在第一次“执行”之后,当我使用 top 列出进程时它就消失了。
    • sorry,能用,是我的错,我刚刚注释掉了,sh有问题,但是我删了,就正常触发了。
    猜你喜欢
    • 2012-09-14
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2015-07-18
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多