Bash script to view runtime of other scripts

I have a main script that runs all the scripts in a folder.

#!/bin/bash for each in /some_folder/*.sh do bash $each done; 

I want to know if one of them takes too long to complete (more than N seconds). For example, executing a script, for example:

 #!/bin/bash ping -c 10000 google.com 

will last a very long time and I want my main script to email me after N seconds.

All I can do is run all the scripts with the #timeout N option, but that will stop them! Is it possible to send me an email and not stop the script?

+7
bash
source share
2 answers

You can do something like this:

 ( sleep 10 ; echo 'Takes a while' | sendmail myself@example.com ) & email_pid=$! bash $each kill $email_pid 

The first command runs in a subshell in the background. First he sleeps and then sends an email. If script $each ends before sleep ends, the subshell is killed without sending email.

+4
source share

Try the following:

 #!/bin/bash # max seconds before mail alert MAX_SECONDS=3600 # running the command in the background and get the pid command_that_takes_a_long_time & _pid=$! sleep $MAX_SECONDS # if the pid is alive... if kill &>/dev/null -0 $_pid; then mail -s "script $0 takes more than $MAX_SECONDS" user@domain.tld < /dev/null fi 

We run the command in the background, and then spam for MAX_SECONDS in // and notify by email if the process takes longer than allowed.

Finally, with your specific requirements:

 #!/bin/bash MAX_SECONDS=3600 alerter(){ bash "$1" & _pid=$! sleep $MAX_SECONDS if kill &>/dev/null -0 $_pid; then mail -s "$2 takes more than $MAX_SECONDS" user@domain.tld < /dev/null fi } for each in /some_folder/*.sh; do alerter "$each" & wait $_pid # remove this line if you wou'd like to run all scripts in // done 
+7
source share

All Articles