0

我正在尝试创建一个脚本,该脚本将杀死一个进程并在发出 kill -9 命令之前确认该进程正在运行,我遇到了一个错误,它总是假设有输出。

#!/bin/sh
rc=$?

#Ask to check for a process to kill
clear
echo "Please enter a process number you would like to kill"
echo ""
read proc
ps -ef | awk '{print $2}' | grep *$proc*
if [[ $rc != 0 ]]; then
        echo "Process not running or already killed"
        sleep 2
        exit $rc
else
        clear
        echo "Killing process..."
        sleep 2
#       kill -9 $proc
fi
4

1 回答 1

1

使用grep $proc是错误的。如果你想杀死 PID 22,它将匹配122,220等。

测试 PID 是否存在的最简单方法是尝试向其发送信号 0:

if kill -0 "$proc" 2>/dev/null
then
    clear
    echo "Killing process..."
    sleep 2
    kill -9 "$proc"
else
    clear
    echo "Process not running or already killed"
    sleep 2
    exit 1
fi

Signal 0 不做任何事情,它只是测试您是否能够向该进程发送信号。

于 2013-07-24T17:07:29.243 回答