2016-11-17 144 views
1

Python腳本我運行與開始一個python腳本在後臺運行bash腳本如何殺死bash腳本

#!/bin/bash 

python test.py & 

因此,如何我可以我殺死bash腳本還腳本?

我用下面的命令來殺死,但輸出no process found

killall $(ps aux | grep test.py | grep -v grep | awk '{ print $1 }') 

我嘗試ps aux | less檢查正在運行的進程,發現python test.py

運行有命令腳本,請幫助,謝謝!

+0

您是否在'ps'的進程信息中找到了關鍵字「test.py」? – staticor

回答

6

使用pkill命令

pkill -f test.py 

(或)使用pgrep搜索的實際進程ID

kill $(pgrep -f 'python test.py') 
+0

在腳本中使用'pkill'實際上非常危險,因爲你會殺死所有名爲參數的進程! –

+0

另一個盲人在中途? – Inian

+0

@RiccardoPetraglia:這個更新對你來說足夠好嗎? – Inian

1

可以使用!得到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的命令可能有風險。

0
ps -ef | grep python 

它將返回 「PID」,則終止該進程通過

sudo kill -9 pid 

例如ps命令的輸出: 用戶13035 4729 0 13點44分/ 10 00:00:00蟒(這裏13035是pid)

+0

'kill -9'命令與'kill'有不同的行爲。使用'-9'選項時請注意。 –

0

隨着bashisms的使用。

#!/bin/bash 

python test.py & 
kill $! 

$!是在後臺啓動的最後一個進程的PID。如果您在後臺啓動多個腳本,您也可以將它保存在另一個變量中。