Last active
May 10, 2019 08:41
-
-
Save panpf/f0041b1bf6d6d1995516a71da59cc1d5 to your computer and use it in GitHub Desktop.
shell 写一个监控脚本,可执行任意命令,命令执行失败退出码非 0 发送报警邮件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 如果需要监控指定命令的执行结果,失败时自动发邮件,就只需在最前面用此命令执行即可,例如 monitor echo "hello world" | |
# 得到当前脚本文件所在的绝对路径 | |
basePath=$(cd `dirname $0`; pwd) | |
# 执行并记录状态码 | |
# 如果原本参数里有双引号或单引号的话,直接执行 '$@',会失败 | |
# 用 echo "$@" 打印后看不到原本的双引号或单引号,例如 hive -e "select * from test" 就会变成 hive -e select * from test | |
# 使用 exec 可正常执行,但是 exec 后面的代码就不会再执行了,所以需要将 exec 包装一下,原本的退出码也会正常返回 | |
${basePath}/monitor_exec_wrapper "$@" | |
result=$? | |
echo "Result: ${result}" | |
# 恢复原本参数中的引号,单引号会被恢复成双引号,因此此结果只能做参考 | |
originParams="" | |
whitespace="[[:space:]]" | |
blank_str=" " | |
for i in "$@" | |
do | |
if [[ $i =~ $whitespace ]]; then | |
i="\"$i\"" | |
fi | |
originParams=${originParams}${blank_str}${i} | |
done | |
echo "originParams: ${originParams}" | |
# 执行失败发邮件 | |
if [[ ${result} -ne 0 ]]; then | |
echo "Shell script execute failed. Script: ${originParams}. result: ${result}" | |
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# exec 命令后面的命令不会被执行,如果将 exec 包装一下就可以继续执行了 | |
exec "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment