我在退出 while 循环中的 bash 脚本时遇到问题:
while read -r dir event name; do
case $event in
OPEN)
chown $VHOST:$VHOST $WEBPATH/$name;
echo "The file \"$name\" was created (not necessarily writable)";
;;
WRITE)
echo "The file \"$name\" was written to";
;;
DELETE)
echo "The file \"$name\" was deleted";
exit 0;
;;
esac
done < <(/usr/bin/inotifywait -m $WEBPATH)
该循环正确侦听给定目录中的文件更改,到目前为止一切顺利。
这也显示在控制台输出上:
root #: bash /var/scriptusr/letsencrypt/dir-change
Setting up watches.
Watches established.
The file "tes" was created (not necessarily writable)
The file "tes" was deleted
root #:
显然,脚本似乎退出得很好,但是当您在进程树中搜索它时,它仍然存在:
root #: ps aux | grep dir-
root 5549 0.0 0.0 14700 1716 pts/0 S 14:46 0:00 bash /var/scriptusr/letsencrypt/dir-change
root 5558 0.0 0.0 14184 2184 pts/1 S+ 14:46 0:00 grep dir-
root #:
所以我的问题是如何真正退出脚本?
答案1
经过一番搜索后,我想出了一个解决方案。
该问题源于inotifywait
@mikeserv 在上面的评论中所述的 subshell。
所以我必须为其编写一个清理方法。我的脚本:
#!/bin/bash
#
#
# script for immediatly changing the owner and group of the let's encrypt challenge file in the given webroot
Pidfile="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/run-file-chowner.pid
echo $$ > $Pidfile
function terminate_process () {
trap - SIGHUP SIGINT SIGTERM SIGQUIT
printf "\nTerminating process...\n"
rm "$Pidfile" > /dev/null 2>&1;
kill -- -$$
exit $1
}
function main () {
trap terminate_process SIGHUP SIGINT SIGTERM SIGQUIT
local OPTIND D opt
while getopts D: opt;
do
case $opt in
D)
Domain=$OPTARG;;
esac
done
shift $((OPTIND-1))
case $Domain in
'domain-b.com')
VHost="doma-www"
;;
'domain-a.com')
VHost="domb-www"
;;
*)
printf "\nScript usage : [ $0 -D \"example.com\" ]\n\n"
exit 1;
;;
esac
WebPath=/var/www/$Domain/$VHost/htdocs/public/.well-known/acme-challenge
inotifywait -m $WebPath | while read -r dir event name; do
case $event in
CREATE)
chown $VHost:$VHost $WebPath/$name
printf "\nOwner and group of \"$name\" were changed to $VHost...\n"
;;
DELETE)
printf "\nThe file \"$name\" was deleted\n"
terminate_process 0
;;
*)
printf "\nEvent $event was triggered.\n"
;;
esac
done
}
main "$@"
这是创建和删除监视文件夹中的文件时的输出:
root #: bash file-chowner -D dom-a.com
Setting up watches.
Watches established.
Owner and group of "test" were changed to doma-www...
Event OPEN was triggered.
Event ATTRIB was triggered.
Event CLOSE_WRITE,CLOSE was triggered.
Event ATTRIB was triggered.
The file "test" was deleted
Terminating process...
Terminated
Terminating process...
Terminated