Search code examples
linuxbashfor-loopsleepkill

'For' loop and sleep in a Bash script


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?


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