Tomas
Tomas

Reputation: 514

Kill Command in linux

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

Answers (6)

Laurent C.
Laurent C.

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

slm
slm

Reputation: 16416

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'

Upvotes: 2

Rustam
Rustam

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

drkunibar
drkunibar

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

chaos
chaos

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

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

Related Questions