Question

I have a Bash script with a for loop, and I want to sleep for X seconds.

#!/bin/sh
for i in `seq 8`;
    do ssh w$i 'uptime;
    ps -elf|grep httpd|wc -l;
    free -m;
    mpstat';
done &
pid=$!
kill -9 $pid

In Bash: sleep 2 sleeps for two seconds. How can I kill the pid automatically after two seconds?

Was it helpful?

Solution

Like suggested in the comments

#!/bin/sh
for i in `seq 8`; 
    do ssh w$i 'uptime;
    ps -elf|grep httpd|wc -l;
    free -m;
    mpstat'; 
done &
pid=$!
sleep 2
kill -9 $pid

In this version, one ssh process may stay alive forever. So maybe it would be better to kill each ssh command separately:

#!/bin/sh
for i in `seq 8`; 
    do ssh w$i 'uptime;
    ps -elf|grep httpd|wc -l;
    free -m;
    mpstat' &;
    pid=$!
    sleep 0.3
    kill $pid
done

OTHER TIPS

You need to put your loop in a wrapper:

Your script (I call it foo.sh)

#!/bin/sh
for i in `seq 8`; 
    do ssh w$i 'uptime;
    ps -elf|grep httpd|wc -l;
    free -m;
    mpstat'; 
done

The wrapper

#!/bin/sh
foo.sh &
pid=$!
sleep 3         #sleep takes number of seconds
kill $pid

You also can check if your process already exists by ps -p $pid -o pid | grep $pid

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top