代码之家  ›  专栏  ›  技术社区  ›  dr Hannibal Lecter

bash脚本,检查错误,日志记录

  •  7
  • dr Hannibal Lecter  · 技术社区  · 15 年前

    这是给巴什福巫师的。不,事实上,我只是开玩笑,你们可能都知道,除了我……

    我正在尝试创建备份外壳脚本。这个想法相当简单:在一个超过7天的文件夹中查找文件,tar/gzip将它们发送到另一个目录,然后删除它们。问题是,我不确定是否有足够的权限在目标目录中创建tar/gzip文件。是否有任何(适当的)方法来检查文件是否创建成功,如果创建成功,请删除文件。否则,跳过该部分,不要破坏客户的数据。我听说他们不太喜欢这个。

    以下是我目前为止的情况:

    01: #!/bin/bash
    02: 
    03: ROOTDIR="/data/www"
    04: 
    05: TAR="${ROOTDIR}/log/svg_out_xml/export_out_ack_$(date +%Y-%m-%d).tar"
    06: cd ${ROOTDIR}/exchange/export/out_ack/
    07: find . -mtime +7 -type f -print0 | xargs -0 tar -cf "${TAR}"
    08: gzip ${TAR}
    09: find . -mtime +7 -type f -print0 | xargs -0 rm -f
    

    基本上,我需要检查第7行和第8行的所有内容是否都正常,如果正常,就执行第9行。

    另外,我想对这些操作制作一个日志文件,这样我就知道一切都很好了(这是一个夜间cron作业)。

    4 回复  |  直到 15 年前
        1
  •  6
  •   Dennis Williamson    15 年前

    对于日志记录,可以用大括号括住脚本的各个部分,并将stdout重定向到日志文件:

    {
        script_command_1
        script_command_2
        script_command_3
    } >> /path/to/log_file
    
        2
  •  12
  •   Idelic    15 年前

    对于日志记录,可以安排在标准输出和/或标准错误上写入的所有输出转到文件。这样,您就不需要重定向每个命令的输出:

    # Save standard output and standard error
    exec 3>&1 4>&2
    # Redirect standard output to a log file
    exec 1>/tmp/stdout.log
    # Redirect standard error to a log file
    exec 2>/tmp/stderr.log
    
    # Now the output of all commands goes to the log files
    echo "This goes to /tmp/stdout.log"
    echo "This goes to /tmp/stderr.log" 1>&2
    ...
    
    # Print a message to the original standard output (e.g. terminal)
    echo "This goes to the original stdout" 1>&3
    
    # Restore original stdout/stderr
    exec 1>&3 2>&4
    # Close the unused descriptors
    exec 3>&- 4>&-
    
    # Now the output of all commands goes to the original standard output & error
    ...
    

    要仅在前一个命令成功时执行命令,可以使用条件将其链接:

    # Execute command2 only if command1 succeeds, and command3 only if both succeed:
    command1 && command2 && command3
    
    # Execute command2 only if command1 fails
    command1 || command2
    

    所以你可以做像

    { find . -mtime +7 -type f -print0 | xargs -0 tar -cf "${TAR}" &&
      gzip ${TAR} && 
      find . -mtime +7 -type f -print0 | xargs -0 rm -f } || 
        { echo "Something failed" 1>&2; exit 1 }
    

    或在日志输出中提供详细信息:

    find . -mtime +7 -type f -print0 | xargs -0 tar -cf "${TAR}" || 
      { echo "find failed!!" 1>&2; exit 1 }
    gzip ${TAR} || 
      { echo "gzip failed!!" 1>&2; exit 1 }
    find . -mtime +7 -type f -print0 | xargs -0 rm -f || 
      { echo "cleanup failed!!" 1>&2; exit 1}
    
        3
  •  6
  •   falstro    15 年前

    简单的出路,但没有明确的错误消息添加 -e 去舍邦,也就是说。 #!/bin/sh -e 如果命令失败,将导致shell退出。

    克罗恩应该通过邮件给你一个错误信息,我想。

    不过,如果你想进行全面的备份计划,我建议你使用一些已经做过的东西。外面有一群人,大多数人工作得很好。

        4
  •  3
  •   Ignacio Vazquez-Abrams    15 年前

    GNU焦油 --remove-files 这将在文件添加到存档后删除它们。 v 将导致它在添加文件时列出文件。 z 将在空中通过gzip输送焦油。

    你的 find 解决方案是Racy的;一个文件可能适合调用之间的条件,因此会被删除,但不会备份。