Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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?

like image 800
Tomas Avatar asked Oct 01 '22 03:10

Tomas


1 Answers

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
like image 54
Mathias Avatar answered Oct 13 '22 10:10

Mathias