2013-10-12 81 views
7

我有一个运行文件夹中所有脚本的主脚本。Bash脚本来观察其他脚本的执行时间

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

我想知道他们中的一个执行是否持续太久(超过N秒)。对于脚本的执行例子如:

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

会持续很长,我想N次后,我的主要脚本发邮件给我。

我现在所能做的就是使用#timeout N选项运行所有脚本,但它会阻止它们! 是否可以给我发电子邮件而不是停止执行脚本?

+0

并行运行它们是一个问题(加载明智等)?因为你可以同时在后台运行它们,并检查它们。 – Wrikken

回答

4

你可以做这样的事情:

(sleep 10 ; echo 'Takes a while' | sendmail [email protected]) & 
email_pid=$! 
bash $each 
kill $email_pid 

的第一个命令是在后台运行子shell。它首先睡一会儿,然后发送电子邮件。如果脚本$each在睡眠到期之前完成,则不会发送邮件就会终止子shell。

7

试试这个:

#!/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 

我们在后台运行的命令,然后睡在// MAX_SECONDS和警报通过电子邮件,如果过程比允许什么更多。

最后,您的具体要求:

#!/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 
+0

这是否会杀死正在运行的脚本,与OP所要求的相反? – Thomas

+0

对不起,忘记了'-0'(只是为了测试pid是否还活着,不杀它) –