gitlab 管道在 grep 处失败,如何修复?

Jor*_*-El 7 grep sh gitlab-ci

我有 gitlab 管道,在执行结束时,会生成一个文本文件。在其中,我试图搜索带有错误的字符串,并希望在管道中显示作业失败。

所以。我在最后添加了以下部分代码。

.check_remote_log: &check_remote_log

- ls -la

- returnCode=$(grep -c "Error:" outfile)

- echo "Return code received $returnCode"

- if [ $returnCode -ge 1 ]; then exit 1; fi
Run Code Online (Sandbox Code Playgroud)

并在步骤结束时将其称为

  • echo“现在检查日志文件中的 returnCode”
  • *检查远程日志

我在输出中观察到的是,正如我在 ls 命令中看到的那样,文件正在生成。但它在 grep 步骤失败。

错误屏幕

但当我在 Linux 机器上单独运行时,这些命令是有效的。请建议。

即使我尝试了下面的命令,但给出了不同的错误。

if [[ $(grep "Error" outfile) ]] ; then exit 1; else echo "No errors in outfile"; fi
Run Code Online (Sandbox Code Playgroud)

错误

sh: 0/1: unknown operand
Run Code Online (Sandbox Code Playgroud)

当输出也有错误时,得到如下。

在此输入图像描述

Kam*_*Cuk 9

作业失败:退出代码 1

man grep

Exit Status

Normally, the exit status is 0 if selected lines are found and 1 otherwise. [...]
Run Code Online (Sandbox Code Playgroud)

如果您想忽略命令的退出状态,通常添加|| :|| true|| :在 YAML 文件中不能很好地工作。

- output=$(grep -c "Error:" outfile) || true
Run Code Online (Sandbox Code Playgroud)

如果你想存储退出状态,请将其放在一行中,这样 gitlab 就不会检测到它。阅读文档https://docs.gitlab.com/ee/ci/yaml/script.html#ignore-non-zero-exit-codes

- output=$(grep -c "Error:" outfile); returncode=$?
- returncode=0 ; output=$(grep -c "Error:" outfile) || returncode=$?
Run Code Online (Sandbox Code Playgroud)

如果你想检查 outfile 是否有错误,请将其放在 if 中。

- if grep -q "Error:" file; then echo has error; exit 1; else echo has no error; fi
# or multiline yaml
- |
  if grep -q "Error:" file; then
     echo has error;
     exit 1;
  else
     echo has no error;
  fi
# or depending on gitlab checking exit status
# but does not handle when file does not exists, or read error, etc.
- '!' grep -q "Error:" file
Run Code Online (Sandbox Code Playgroud)

如果您想检查文件是否没有字符串,则必须显式检查退出状态是否等于 1。我会这样做:

- grep -HnC 3 "Error:" file ; [ "$?" -eq 1 ]
Run Code Online (Sandbox Code Playgroud)