检查errexit,在屏幕上显示stderr,stdout并通过电子邮件发送

时间:2012-12-03 13:48:24

标签: bash

  

可能重复:
  Bash Beginner Check Exit Status

下面是一个示例bash脚本。我需要用errexit检查整个脚本的错误,即set -e。我的目的是在屏幕上显示stderr和stdout并同时存储在文件中以通过电子邮件发送。

我的真实剧本很大,包括5个函数和许多reqular expersion。但所有退出都很好,但是当root用户执行if条件结束时,它结束并等待tee退出..我如何从tee写的test.log获得退出状态。

我的尝试是检查脚本是否以errexit代码退出,并且在test.log中写入的stderr和std out部分显示在屏幕上并通过EMAIL发送。

让我知道如何才能最好地实现这一目标。

    #!/bin/bash
    #Checks root permission
    if [ $(id -u) != "0" ]; then
       echo " "
       echo -e "\e[5mYou must be the superuser to run this script" >&2
       su -c "$0 $@"
    #   echo " "
       exit 
    fi

    ( (set -e
    #some commands here.. which can only be done with root user.
    ....
    ...

    ALERT_MAIL=abc@123.com

    touch test.log
    chown user.user test.log

    function one()
    {
    ..
    }
    export -f one

    #below are some of the commands to be executed with user strickly.

    su user -c 'set -e && echo $(date +%m%d%Y) && one && echo "exit"'

   # Again some of commands to be exuted by root user so

    if [ $? -eq 0 ]; then
    ....
    else..
    ...
    exit1
    fi

    ) 2>&1) | tee test.log            # i tested the tee output (stderr&stdout) and on screen (stderr&stdout) . redirect OK.


    #I am trying for check as below, perhaps any idea how to achive it..


    if [ errexit ]; then
    mail -s "script stopped with errr" abc@123.com < test.log
    else
    mail -s "script excuted successfully" abc@123.com < test.log
    fi
    exit

0 个答案:

没有答案