
我正在從不同的路徑運行 3 個具有相同檔案名稱的應用程式:
$ ~/app1/main
$ ~/app2/main
$ ~/app3/main
我想創建一個 bash 腳本,它接受可執行檔的全名並殺死該應用程式。
$ ./my_killer.sh /home/me/app2/main
我該怎麼做,特別是如何透過全名殺死應用程式?
答案1
如果您只需要支援 Linux(鑑於您的問題被標記為 linux,我猜就是這種情況),您可以使用符號/proc/%d/exe
連結。
以下是執行此操作的腳本的範例。
#!/bin/bash
if [ "$#" != 1 ] || [ "$1" = "" ]
then
echo "Usage: $0 <full-exe-path>" 1>&2
exit 1
fi
shopt -s extglob
cd /proc
for PID in [1-9]*([0-9])
do
if [ "$(readlink "$PID"/exe)" = "$1" ]
then
kill "$PID"
fi
done
需要注意的一個警告是,如果進程 ID 是核心執行緒或不屬於您,readlink
則會失敗,並且"$(readlink "$PID"/exe)"
計算結果為空字串。為了避免嘗試終止所有這些進程,如果$1
是空字串,腳本將拒絕執行任何操作。
另請注意,此腳本使用了extglob
允許匹配目錄的功能,[1-9]*([0-9])
這意味著間隔中的一個字元1-9
後跟間隔中的任意數量的字元0-9
。
答案2
我在帶有管道的單襯裡執行此操作(您需要gawk
和xargs
):
$>ps -ax | grep "/app2/main" | grep -v "grep" | gawk '{print $1}' | xargs kill
這裡發生了什麼事?
ps -ax # — list all processes in extended format
grep "/app2/main" # — show only processes that contain "/app2/main"
grep -v "grep" # — sort out the previous grep process with the mentioned string
gawk '{print $1}' # — use gawk to pick only the first column (process id)
xargs kill # — use xargs to pass pid to kill as an argument
這有效地向您需要的進程發送終止訊號。如果您想要一個帶有參數的簡短命令,您可以將其包裝在 bash 腳本中。