gpt4 book ai didi

shell - 在日志文件中搜索 - 退出代码

转载 作者:行者123 更新时间:2023-12-04 12:39:28 26 4
gpt4 key购买 nike

我有一些遗留软件需要在 Control-M 下自动化。这些工作是在 Windows 2008R2 下进行的。

如果这些作业运行正常,则它们的退出代码为 0,而且如果它们可以管理一些错误。当特定字符串在日志中时,我需要发出警报。
该字符串不在可执行文件的输出中。

我为此实现了另一项工作。它会在文件中搜索一个字符串,并在“On Do Actions”中搜索该语句。

为了在输出中包含语句,我认为使用类似 的东西grep .我用了:

  • findstr
    findstr "myerrorcode" D:\Log\greptest_%%$ODATE..log
  • grep cygwin

  • 在这两种情况下,我都有相同的情况:
  • 如果找到字符串,则一切正常
  • 如果文件未找到或无法打开,grep 或 findstr 返回退出代码 = 1。这没问题,因为作业必须引发错误。

  • 但问题是:当在文件中找不到字符串时,grep 和 findstr 都有一个返回码 = 1。

    如何区分文件无法打开以及一切正常但未找到日志中的 sring 的情况?

    最佳答案

    您应该可以使用 grep的退出状态来检测失败的原因。根据POSIX grep docs , 退出状态部分:

    EXIT STATUS

    The following exit values shall be returned:

    0 One or more lines were selected.
    1 No lines were selected.
    >1 An error occurred.


    GNU grep 类似(一致,但更具体):

    Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. [...] Other grep implementations may exit with status greater than 2 on error.



    例如,在 bash ,您可以使用 case命令来处理这样的多个分支:
    #!/bin/bash

    # search for error code in file
    grep code file

    # store the exit status in variable err
    err=$?

    # test several cases
    case $err in
    0) echo All good.;;
    1) echo Code not found.;;
    *) echo Error reading from file.;;
    esac

    关于shell - 在日志文件中搜索 - 退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48327083/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com