我正在尝试编写一个捕获退出信号并终止的脚本。我不想使用通常的 bash 陷阱方法,而是每 10 秒监视一次文件创建并在终止前清理一些内容。
这是我尝试过的:
poll_time=10 // poll every 10 seconds
((term_time=$SECONDS+240)) // monitor until 4 min from current script time exec
while (( $SECONDS < $term_time)) do
if [[ -r $some_path/file.txt ]]; then
cleanup_function
exit
fi
sleep ${poll_time}
done
//if file doesnt exit continue with below code
//blah blah blah ....
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?上面的代码行会起作用吗?
inotifywait
frominotify-tools
是你需要的(至少要看看)。像这样的行将执行您的脚本打算执行的相同技巧:
inotifywait -e create --timeout 240 "${some_path}/file.txt" && { cleanup_function; exit ; }
Run Code Online (Sandbox Code Playgroud)
差异inotifywait
以基于事件的方式工作,因此不需要轮询或睡眠。