GitHub Action执行失败:grep命令返回exit code 1问题求助
问题排查与解决方案
错误根源
1. grep命令的退出码问题
grep -c在未找到匹配内容时会返回退出码1,而GitHub Actions默认会将非0退出码视为step执行失败,直接终止流程,不会继续执行后续的判断逻辑。
2. 错误获取PR作者信息
在pull_request事件中,GITHUB_ACTOR指向的是触发Action运行的用户(比如手动触发同步的人),而非发起PR的实际作者。正确的PR作者用户名应该从github.event.pull_request.user.login获取。
3. 仓库 checkout 配置缺失
默认的actions/checkout@v3只会拉取单个提交,没有拉取完整分支历史,后续执行git push会失败。
4. 权限与文件存在性问题
- 默认
GITHUB_TOKEN没有推送权限到仓库,需要显式配置权限; - 如果项目中还没有
AUTHORS.md文件,grep会直接报错,需要先判断文件是否存在。
修正后的完整Action代码
name: Add Contributor to AUTHORS.md on: pull_request: types: - opened - synchronize permissions: contents: write # 赋予推送代码的权限 jobs: add_contributor: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 # 升级到v4版本,默认支持完整分支拉取 with: ref: ${{ github.head_ref }} # 拉取PR的源分支 - name: Check if contributor already exists id: check_contributor run: | # 先判断AUTHORS.md是否存在,不存在则直接标记为未存在 if [ ! -f AUTHORS.md ]; then echo "exists=false" >> $GITHUB_OUTPUT exit 0 fi # 使用grep -q + 逻辑判断,忽略grep的退出码 if grep -q -F "${{ github.event.pull_request.user.login }}" AUTHORS.md; then echo "exists=true" >> $GITHUB_OUTPUT else echo "exists=false" >> $GITHUB_OUTPUT fi - name: Get contributor's full name id: get_full_name if: steps.check_contributor.outputs.exists == 'false' run: | username=${{ github.event.pull_request.user.login }} access_token=${{ secrets.GITHUB_TOKEN }} # 使用jq处理API返回,避免空值问题 full_name=$(curl -s -H "Authorization: token $access_token" "https://api.github.com/users/$username" | jq -r '.name // .login') echo "full_name=$full_name" >> $GITHUB_OUTPUT - name: Append contributor to AUTHORS.md id: append_contributor if: steps.check_contributor.outputs.exists == 'false' run: | full_name=${{ steps.get_full_name.outputs.full_name }} # 如果文件不存在,先创建并添加表头(可选,根据你的格式调整) if [ ! -f AUTHORS.md ]; then echo "| Full Name | GitHub Username |" >> AUTHORS.md echo "|-----------|-----------------|" >> AUTHORS.md fi echo "| $full_name | ${{ github.event.pull_request.user.login }} |" >> AUTHORS.md - name: Commit and push changes if: steps.check_contributor.outputs.exists == 'false' run: | git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add AUTHORS.md git commit -m "Add ${{ github.event.pull_request.user.login }} to AUTHORS.md" git push
关键修改点说明
修复
grep退出码问题:- 先判断
AUTHORS.md是否存在,不存在直接标记为未存在; - 使用
grep -q(静默模式)配合if判断,忽略grep的退出码,只关注匹配结果。
- 先判断
正确获取PR作者:
- 替换
GITHUB_ACTOR为${{ github.event.pull_request.user.login }},确保获取的是发起PR的作者用户名。
- 替换
配置权限与checkout参数:
- 添加
permissions: contents: write,赋予Action推送代码的权限; - 升级到
actions/checkout@v4,并指定ref: ${{ github.head_ref }}拉取PR的源分支,保证后续push正常执行。
- 添加
处理文件不存在的情况:
- 在追加内容前判断文件是否存在,不存在则先创建并添加表头(可根据你的
AUTHORS.md格式调整)。
- 在追加内容前判断文件是否存在,不存在则先创建并添加表头(可根据你的
优化API调用逻辑:
- 使用
jq的//运算符,当name字段为空时直接使用login作为 fallback,简化判断逻辑。
- 使用
内容的提问来源于stack exchange,提问作者Garvit Singhal
相关产品推荐
相关产品推荐

