“无输出”返回代码Shell脚本

时间:2013-07-24 17:00:27

标签: linux shell scripting io rc

我正在尝试创建一个脚本来杀死进程并在发出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

1 个答案:

答案 0 :(得分:1)

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

测试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

信号0没有做任何事情,只是测试你是否能够向该过程发送信号。