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

问题描述 投票:0回答:2

我有 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

并在步骤结束时将其称为

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

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

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

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

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

sh: 0/1: unknown operand

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

grep sh gitlab-ci
2个回答
9
投票

作业失败:退出代码 1

来自

man grep

Exit Status

Normally, the exit status is 0 if selected lines are found and 1 otherwise. [...]

如果您想忽略命令的退出状态,通常添加

|| :
|| true
|| :
在 YAML 文件中不能很好地工作。

- output=$(grep -c "Error:" outfile) || true

如果你想存储退出状态,请将其放在一行中,这样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=$?

如果你想检查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

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

- grep -HnC 3 "Error:" file ; [ "$?" -eq 1 ]

0
投票

请使用

awk
代替。它不会在管道中为您提供“exit 1”状态代码,并且可以作为
grep
替代品。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.