For loop and sleep in bash script

I have a bash script with a for loop, 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 2sleeps for 2 seconds. I want to kill pid automatically in 2 seconds.

+4
source share
2 answers

As 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 can stay alive forever. Therefore, it might 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
0
source

You need to put your loop in a shell:

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

Wrapper

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

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

+2
source

Source: https://habr.com/ru/post/1534780/


All Articles