可以使用!
得到PID更防呆方式最後一個命令。
我建議類似於以下的東西,這也檢查,如果你想運行的進程已經運行:當你想殺死它
#!/bin/bash
if [[ ! -e /tmp/test.py.pid ]]; then # Check if the file already exists
python test.py & #+and if so do not run another process.
echo $! > /tmp/test.py.pid
else
echo -n "ERROR: The process is already running with pid "
cat /tmp/test.py.pid
echo
fi
然後:
#!/bin/bash
if [[ -e /tmp/test.py.pid ]]; then # If the file do not exists, then the
kill `cat /tmp/test.py.pid` #+the process is not running. Useless
rm /tmp/test.py.pid #+trying to kill it.
else
echo "test.py is not running"
fi
當然,如果在命令啓動後一段時間內發生殺戮,您可以將所有內容放在同一個腳本中:
#!/bin/bash
python test.py & # This does not check if the command
echo $! > /tmp/test.py.pid #+has already been executed. But,
#+would have problems if more than 1
sleep(<number_of_seconds_to_wait>) #+have been started since the pid file would.
#+be overwritten.
if [[ -e /tmp/test.py.pid ]]; then
kill `cat /tmp/test.py.pid`
else
echo "test.py is not running"
fi
如果您希望能夠同時運行更多具有相同名稱的命令,並且能夠選擇性地殺死它們,則需要對該腳本進行小量編輯。告訴我,我會盡力幫助你!
有了這樣的事情,你確定你正在殺死你想殺的東西。類似pkill
或grey ps aux
的命令可能有風險。
您是否在'ps'的進程信息中找到了關鍵字「test.py」? – staticor