'For' loop and sleep in a Bash script
17,281
Solution 1
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
Solution 2
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
Author by
Tomas
Updated on June 04, 2022Comments
-
Tomas almost 2 years
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?