# Check if VPNC is already running, otherwise start it
if ( ps -ef | grep -v grep | grep -v vpnc_ondemand | grep -v less | grep vpnc > /dev/null ) ; then
echo "Shell script is already running then dont run this script and terminate the script".
exit
else
echo "run the other part of script "
我希望如果这个过程已经在运行,那么整个脚本就会自行终止,并且不会运行脚本的进一步部分。
或者我已经写好的这段代码会执行它我在寻找什么
答案1
如果您需要这种监督管理,我会考虑 Upstart。通过运行创建一个新文件sudoedit /etc/init/vpnc.conf
并复制以下内容:
start on (started networking)
respawn
exec /usr/sbin/vpnc --no-detach
然后只需sudo start vpnc
首次启动它(之后它将自动启动)。Upstart 将通过其 PID 跟踪进程。无需脚本黑客。
答案2
使用@muru 的建议,这里有一个可以执行您想要的操作的 bash 脚本:
#!/usr/bin/env bash
process='vpnc$'
if pgrep $process > /dev/null; then # Here we are using the fact that if pgrep returns 0, the process is running
echo "Shell script is already running then dont run this script and terminate the script".
exit 1 # A number different of zero is good to point out that something went wrong
else
echo "run the other part of script "
fi
但是@Oli 的回答更适合您的问题(服务器上的程序管理)。