我有一个主脚本,它运行文件夹中的所有脚本.
#!/bin/bash
for each in /some_folder/*.sh
do
bash $each
done;
Run Code Online (Sandbox Code Playgroud)
我想知道其中一个执行是否持续时间太长(超过N秒).例如执行脚本,例如:
#!/bin/bash
ping -c 10000 google.com
Run Code Online (Sandbox Code Playgroud)
将持续很长时间,我希望我的主要脚本在N秒后通过电子邮件发送给我.
我现在所能做的就是用#timeout N选项运行所有脚本但它会阻止它们!是否可以通过电子邮件发送给我,而不是停止执行脚本?
试试这个 :
#!/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
Run Code Online (Sandbox Code Playgroud)
我们在后台运行命令,然后在//中调用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" 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
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
( sleep 10 ; echo 'Takes a while' | sendmail myself@example.com ) &
email_pid=$!
bash $each
kill $email_pid
Run Code Online (Sandbox Code Playgroud)
第一个命令在后台的子 shell 中运行。它首先休眠一段时间,然后发送电子邮件。如果脚本$each在睡眠到期之前完成,则子 shell 将被终止而不发送电子邮件。