inotifywait 脚本无限期地监视文件,并重新启动进程需要建议

inotifywait 脚本无限期地监视文件,并重新启动进程需要建议

我正在尝试编写一个脚本,该脚本将在使用 inotify 写入应用程序配置文件时重新启动进程。该脚本应该根据运行的主机而采取不同的行为:如果它在“主”服务器上运行,则脚本应重新启动进程,并将文件 scp 到其他“辅助”主机。如果它在“辅助”服务器上运行,则应该重新启动该进程。

我在后台运行脚本,我注意到脚本的进程在一段时间后终止,并且在辅助主机上,脚本重新启动进程运行多次,而不是一次。

    #!/bin/bash
# Script to watch APP application file for write changes.
# If APP is written to and saved, on server0, restart APP and check if its running.
# Then push to other servers with userone account.
# If not on server0, push simply restart APP.

declare -a APP_HOSTS=("server0" "server1" "server3" "pushserver0" "pushserver1" "pushserver3" "vumitest")
declare -a my_needed_commands=("/opt/APP/conf/application.conf" "inotifywait" "service")
HOSTNAME=$(hostname -s)

missing_commands()
{
    local missing_counter=0
    for needed_command in "${my_needed_commands[@]}"; do
        if ! command -v "$needed_command" >/dev/null 2>&1; then
            printf "Command not found in PATH: %s\n" "$needed_command" >&2
            ((missing_counter++))
        fi
    done

    if ((missing_counter > 0)); then
        printf "Minimum %d commands are missing in the PATH, aborting.\n" "$missing_counter" >&2
        exit 1
    fi
}

restart_and_scp()
{
    local host_count=0
    local restofthem=("${APP_HOSTS[@]}")
    unset restofthem[0]
    if service APP restart >/dev/null 2>&1; then
        for each in "${restofthem[@]}"; do
            scp -Cqv "${my_needed_commands[0]}" userone@"$each":/opt/APP/conf >/dev/null 2>&1
            ((host_count++))
            if [ host_count -eq "${#restofthem[@]}" ]; then
                break
            fi
        done
    fi
}

restart_APP()
{
    service APP restart >/dev/null 2>&1
}

prime_watch()
{
    inotifywait -mrq -e close_write "${my_needed_commands[0]}" | \
    while read filename; do restart_and_scp; done
}

other_watch()
{
    inotifywait -mrq -e modify "${my_needed_commands[0]}" | \
    while read filename; do restart_APP; done
}

setup_watch()
{
    if [ ! -z "$1" ]; then
        prime_watch 
    else
        other_watch
    fi
}

main()
{

    if [[ "${APP_HOSTS[0]}" =~ "${HOSTNAME}" ]]; then 
        setup_watch prime
    else
        setup_watch
    fi 
    exit
}

main "$@"

请问我做错了什么?

相关内容