2013-10-12 79 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是否還活着,不殺它) –