且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在shell脚本中执行kill命令后未执行任何命令

更新时间:2023-11-30 10:39:52

您的脚本有效.我能看到未执行回显的唯一原因是$ 1的某些值和脚本文件名结合在一起,以便您的脚本PID也被收集,从而使脚本自杀.

Your script works. The only reason I can see for the echo not being executed is that some value of $1 and the script file name combine so that your script PID is also gathered, thereby making the script suicide.

PIDS行产生一个运行ps,grep和另一个grep的进程-这样您就不会在PIDS中找到运行grep的进程,但是父进程本身呢?

The PIDS line spawns a process running ps, grep, another grep -- so you won't find in PIDS the processes running grep, but what about the parent process itself?

尝试:

#!/bin/bash
PIDS=$(ps -e | grep $1 |grep -v grep | awk '{print $1}' | grep -v "^$$\$" )
kill -s SIGINT $PIDS
echo "Done sendings signal"

或以适当的安全抓斗一个接一个地铺设管道.

or run the pipes one after the other with suitable safety greps.

很明显,"$ 1"选项选择过多.所以我要像这样重写脚本:

it is evident that the "$1" selection is selecting too much. So I'd rewrite the script like this:

#!/bin/bash
# Gather the output of "ps -e". This will also gather the PIDs of this
# process and of ps process and its subshell.
PSS=$( ps -e )
# Extract PIDs, excluding this one PID and excluding a process called "ps".
# Don't need to expunge 'grep' since no grep was running when getting PSS.
PIDS=$( echo "$PSS" | grep -v "\<ps\>" | grep "$1" | awk '{print $1}' | grep -v "^$$\$" )
if [ -n "$PIDS" ]; then
    kill -s SIGINT $PIDS
else
    echo "No process found matching $1"
fi
echo "Done sending signal."