在Linux中杀死命令

我有一个bash脚本abcd.sh ,其中我想在5秒后杀死这个命令(/usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat')但是在这个脚本中它会在5秒后杀死sleep命令。

 #!/bin/sh /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' & sleep 5 kill $! 2>/dev/null && echo "Killed command on time out" 

尝试

 #!/bin/sh /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' & pid=$! sleep 5 kill $pid 2>/dev/null && echo "Killed command on time out" 

更新:

一个工作的例子(没有特别的命令)

 #!/bin/sh set +x ping -i 1 google.de & pid=$! echo $pid sleep 5 echo $pid kill $pid 2>/dev/null && echo "Killed command on time out" 

您应该使用timeout(1)命令:

 timeout 5 /usr/local/bin/wrun \ 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' 

而是尝试构建自己的机制,为什么不使用timeout命令。

 $ date; timeout 5 sleep 100; date Tue Apr 1 03:19:56 EDT 2014 Tue Apr 1 03:20:01 EDT 2014 

在上面你可以看到timeout已经在5秒(也就是持续时间)之后终止了sleep 100

你的例子

 $ timeout 5 /usr/local/bin/wrun \ 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' 

尝试这个:

 #!/bin/sh /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' & sleep 5 pkill "wrun" && echo "Killed command on time out" 

这是因为变量$! 包含最近的后台命令PID 。 这个背景命令在你的情况下sleep 5 。 这应该工作:

 #!/bin/sh /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' & PID=$! sleep 5 kill $PID 2>/dev/null && echo "Killed command on time out" 

你可以使用像这样的东西:

 #!/bin/sh /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' & PID=`ps -ef | grep /usr/local/bin/wrun | awk '{print $1}'` sleep 5 kill $PID 2>/dev/null && echo "Killed command on time out"