Question

I have a bash script abcd.sh,in which I want to kill this command(/usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat') after 5 sec but in this script it kill sleep command after 5 second.

#!/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"
Was it helpful?

Solution

Try

#!/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"

UPDATE:

A working example (no special commands)

#!/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"

OTHER TIPS

You should use instead the timeout(1) command:

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

Rather then try and construct your own mechanism why not make use of the timeout command.

Example

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

In the above you can see that timeout has terminated the sleep 100 after only 5 seconds (aka. the duration).

Your example

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

Try this:

#!/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"

This is because the variable $! contains the PID of the most recent background command. And this background command is in your case sleep 5. This should work:

#!/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"

You could use something like:

#!/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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top