Hoa*_*Hoa 1 bash ubuntu upstart
在伪代码中,我试图做类似以下的事情
if myService is running
restart myService
else
start myService
Run Code Online (Sandbox Code Playgroud)
如何将上述内容翻译成bash脚本或类似内容?
标准方法是使用PID文件存储服务的PID.然后,您可以使用PID文件中存储的PID来查看服务是否已在运行.
查看/etc/init.d目录下的各种脚本,看看它们如何使用PID文件.另外,/var/run在大多数Linux系统中查看PID文件的存储位置.
您可以执行类似这样的操作,这是处理所有Bourne shell类型shell的一般方法:
# Does the PID file exist?
if [ -f "$PID_FILE" ]
then
# PID File does exist. Is that process still running?
if ps -p `cat $PID_FILE` > /dev/null 2&1
then
# Process is running. Do a restart
/etc/init.d/myService restart
cat $! > $PID_FILE
else
# Process isn't' running. Do a start
/etc/init.d/myService start
cat $! > $PID_FILE
else
# No PID file to begin with, do a restart
/etc/init.d/myService restart
cat $! > $PID_FILE
fi
Run Code Online (Sandbox Code Playgroud)
但是,在Linux上,您可以利用pgrep:
if pgrep myService > /dev/null 2>&1
then
restart service
else
start service
fi
Run Code Online (Sandbox Code Playgroud)
请注意您不使用任何大括号.该if语句对pgrep命令的退出状态进行操作.我正在将STDOUT和STDERR输出到/ dev/null,因为我不想打印它们.我只想要pgrep命令本身的退出状态.
阅读PGREP上的手册
有很多选择.例如,您可能希望用于-x防止意外匹配,或者您可能必须使用-f匹配用于启动服务的完整命令行.