You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在推送到main分支时触发GitHub Actions工作流?

实现GitHub工作流仅在推送到/合并到main分支时运行

要精准实现仅在推送到main分支或合并PR到main分支时触发工作流,不需要冗余的判断逻辑,利用GitHub Actions的on字段就能完成大部分过滤,以下是最简且可靠的配置方案:

1. 基础配置:仅监听推送到main分支

这是最直接的场景,只需要在on.push.branches里指定main分支即可:

name: main_workflow
on:
  push:
    branches: [main] # 仅在推送到main分支时触发工作流
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # 你的具体步骤(比如构建、测试等)

2. 扩展配置:同时监听PR合并到main分支

如果需要在PR合并到main时也触发工作流,需要添加pull_request的closed类型(PR合并属于closed事件的一种,且会附带merged: true标记):

name: main_workflow
on:
  push:
    branches: [main]
  pull_request:
    branches: [main] # 仅针对目标分支为main的PR
    types: [closed] # 仅监听PR关闭事件
jobs:
  build:
    runs-on: ubuntu-latest
    # 仅当PR是合并状态时才执行任务
    if: ${{ github.event_name == 'pull_request' && github.event.pull_request.merged == true }}
    steps:
      # 你的具体步骤

完整整合配置

把两种场景整合,最终的配置如下:

name: main_workflow
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
    types: [closed]
jobs:
  build:
    runs-on: ubuntu-latest
    # 推送时直接执行,PR仅合并时执行
    if: ${{ github.event_name != 'pull_request' || github.event.pull_request.merged == true }}
    steps:
      # 你的具体步骤

你之前遇到的问题解析

  1. 初始配置的冗余判断:你一开始的配置里,on.push.branches: [main]已经完成了推送分支的过滤,后面额外加的if判断完全多余。网页编辑提交时触发工作流是正常的——因为你编辑的就是main分支的文件,推送操作自然会触发。
  2. PR配置的误区:你之前改成pull_request但没加types: [closed],此时GitHub会监听PR的所有事件(比如打开、同步),而且PR事件里的github.ref指向的是PR的头部分支(不是目标分支main),导致你的if判断完全失效,非main分支的PR也会触发工作流。
  3. 回到初始配置后正常的原因:大概率是之前的测试操作或配置缓存有干扰,回到仅监听push: branches: [main]的配置后,GitHub的事件过滤逻辑正常生效,非main分支的推送自然不会触发。

内容的提问来源于stack exchange,提问作者LittleFighter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:05:08