Reputation: 514
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"
Upvotes: 0
Views: 1143
Reputation: 206
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"
Upvotes: 0
Reputation: 16416
Rather then try and construct your own mechanism why not make use of the timeout
command.
$ 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).
$ timeout 5 /usr/local/bin/wrun \
'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'
Upvotes: 2
Reputation: 192
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"
Upvotes: 1
Reputation: 1337
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"
Upvotes: 6
Reputation: 9282
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"
Upvotes: 0
Reputation: 1
You should use instead the timeout(1) command:
timeout 5 /usr/local/bin/wrun \
'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'
Upvotes: 6