Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to watch execution time of other scripts

Tags:

bash

I have a main script which run all the scripts in a folder.

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

I want to know if execution of one of them lasts too long (more than N seconds). For example execution of script such as:

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

will lasts very long, and I want my main script to e-mail me after N second.

All I can do now is to run all scripts with #timeout N option but it stops them! Is it possible to E-mail me and not to stop execution of script?

like image 680
merlin.metso Avatar asked Oct 12 '13 13:10

merlin.metso


People also ask

How do you time a bash script?

Using Bash Shell's TIMEFORMAT The TIMEFORMAT is a string format that will be printed after the execution of the block code inside the time{} wrapper finishes. The %R specifies to print the elapsed time in seconds with milliseconds precision. Let's test our script: $ ./elapsed_time.sh It took 12.008 seconds.

How does bash calculate execution time?

The most common way to measure elapsed time in bash is to utilize the date command, which can show the current system date and time in a configurable format. Using the flexiblity of date 's display format, you can easily calculate elapsed time with different resolutions.

How do I check the runtime of a script in Linux?

You can use ' time ' command to get the execution time of the script. This command will call the Tcl interpreter count times to evaluate script (or once if count is not specified).

How can I run two shell scripts at the same time?

The command to do this is CTRL-B :setw synchronize-panes on. Now you can run scriptName $fruit and view the output on all panes at the same time.


1 Answers

Try this :

#!/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" [email protected] < /dev/null
fi

We run the command in the background, then sleep for MAX_SECONDS in // and alert by email if the process takes more than what is permitted.

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" [email protected] < /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
like image 73
Gilles Quenot Avatar answered Sep 20 '22 06:09

Gilles Quenot