How can I check a file exists and execute a command if not?
I have a daemon I have written using Python. When it is running, it has a PID file located at /tmp/filename.pid. If the daemon isn't running then PID file doesn't exist.
On Linux, how can I check to ensure that the PID file exists and if not, execute a command to restart it?
The command would be
python daemon.py restart
which has to be executed from a specific directory.
[ -f /tmp/filename.pid ] || python daemon.py restart
-f
checks if the given path exists and is a regular file (just -e
checks if the path exists)
the []
perform the test and returns 0
on success, 1
otherwise
the ||
is a C-like or
, so if the command on the left fails, execute the command on the right.
So the final statement says, if /tmp/filename.pid
does NOT exist then start the daemon.
If it is bash scripting you are wondering about, something like this would work:
if [ ! -f "$FILENAME" ]; then
python daemon.py restart
fi
A better option may be to look into lockfile
The other answers are fine for detecting the existence of the file. However for a complete solution you probably should check that the PID in the pidfile is still running, and that it's your program.
链接地址: http://www.djcxy.com/p/24136.html上一篇: 检查文件是否存在,并继续在Bash中退出
下一篇: 如何检查存在的文件并执行命令?