GitHub Actions如何仅在data.xlsx存在时执行commit提交步骤
方案1:通过Actions内置if条件控制步骤执行(推荐)
利用GitHub Actions内置的hashFiles函数直接判断文件是否存在,文件不存在时整个提交步骤直接跳过,不会运行。
直接在原有步骤上新增if字段即可:
# 若data.xlsx存放在子目录下,需要补全对应路径 - name: Commit files if: hashFiles('data.xlsx') != '' run: | git config --local user.name actions-user git config --local user.email "actions@github.com" git add data.xlsx git commit -m "GH ACTION Headlines $(date)" git push origin main -f env: REPO_KEY: ${{secrets.GITHUB_TOKEN}} username: github-actions
方案2:在运行脚本内部加判断
如果需要保留步骤运行记录,只是不想在无文件时报错,可以直接在shell脚本内加存在性判断:
- name: Commit files run: | if [ -f "data.xlsx" ]; then git config --local user.name actions-user git config --local user.email "actions@github.com" git add data.xlsx # 额外判断文件是否有变更,避免存在但无更新时commit报错 if ! git diff --cached --quiet; then git commit -m "GH ACTION Headlines $(date)" git push origin main -f else echo "data.xlsx 存在但内容无更新,跳过提交" fi else echo "data.xlsx 未生成,跳过提交步骤" fi env: REPO_KEY: ${{secrets.GITHUB_TOKEN}} username: github-actions
优化建议
- 把原有的
git add *改为仅添加目标文件git add data.xlsx,避免提交工作区其他意外生成的临时文件 - 新增文件变更判断逻辑,可同时解决「文件存在但内容和历史版本完全一致」时的commit报错问题
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

