我在 Github Actions 作业中有一个步骤:
- name: Check for changes
run: |
diff=$( git diff --name-only 'origin/main' )
changed_files=$( echo $diff | grep -c src/my_folder ) # this fails
# more script lines
# that are unrelated
失败并显示 Error: Process completed with exit code 1.
仅当 grep 未找到任何内容时。
如果 $diff
中有匹配项,则此步骤将按预期进行。但当然它也需要在没有匹配的情况下工作。
我可以在本地或在脚本中毫无问题地运行它,退出代码始终为 0
(在 Mac 上)。
我不明白问题是什么。经过几个小时的反复试验和研究,我了解到显然 grep
在 Github 操作中很棘手,但我没有找到任何提示或适当的文档,我应该如何解决这个确切的案例。
如果我将失败行更改为
echo $( echo $diff | grep -c src/my_folder ) # this works and prints out the result
这可以毫无问题地执行。
但是,即使没有任何发现,我如何将 grep 输出放入我的变量中?
最佳答案
默认情况下,Github Actions 启用 set -e
来运行步骤的命令。这就是为什么中间命令失败可能导致整个步骤失败的原因。要完全控制步骤的命令,您可以这样做:
- name: Check for changes
shell: bash {0}
run: |
diff=$( git diff --name-only 'origin/main' )
changed_files=$( echo $diff | grep -c src/my_folder )
# ...
# ...
或者您可以在步骤脚本的开头禁用默认的 set -e
:
- name: Check for changes
run: |
set +x
diff=$( git diff --name-only 'origin/main' )
changed_files=$( echo $diff | grep -c src/my_folder )
# ...
# ...
关于bash - Github 操作 : Why an intermediate command failure in shell script would cause the whole step to fail?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73066461/