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

Azure DevOps PR触发器无法获取目标分支名,脚本执行报错

问题原因与解决方案

你遇到的System.PullRequest.SourceBranch: command not found错误,本质是Bash将Azure DevOps的预定义变量宏语法当成了命令执行。在Bash脚本中,$(...)是命令替换语法,如果Azure DevOps没有正确解析$(System.PullRequest.SourceBranch)这个宏变量,Bash就会尝试执行System.PullRequest.SourceBranch这个不存在的命令,从而报错。

修正方案

在Bash任务中,引用Azure DevOps预定义变量时,应该使用环境变量格式(大写字母+下划线分隔),而不是直接用宏语法。具体对应关系如下:

  • System.PullRequest.TargetBranch → $SYSTEM_PULLREQUEST_TARGETBRANCH
  • System.PullRequest.SourceBranch → $SYSTEM_PULLREQUEST_SOURCEBRANCH
  • Build.SourceBranch → $BUILD_SOURCEBRANCH

另外,在env块中使用宏语法是没问题的,因为这里是Azure DevOps直接替换变量后传递给Bash环境。

修正后的流水线代码如下:

pr:
 - '*'

pool:
  vmImage: 'ubuntu-latest'

stages:
  - stage: PRValidation
    displayName: PR Validation
    jobs:
    - job: CloneTargetBranch
      displayName: 'Clone Target Branch on PR'
      steps:
        - task: Bash@3
          displayName: 'Debug PR Variables'
          inputs:
            targetType: 'inline'
            script: |
              echo "PR Target Branch : $SYSTEM_PULLREQUEST_TARGETBRANCH"
              echo "PR Source Branch : $SYSTEM_PULLREQUEST_SOURCEBRANCH"
              echo "Build Source Branch: $BUILD_SOURCEBRANCH"
              printenv | sort

        - task: Bash@3
          displayName: 'Clone Target Branch'
          env:
            TARGET_BRANCH: $(System.PullRequest.TargetBranch)   # PR Target branch
            ACCESS_TOKEN: $(System.AccessToken)
            REPO_URL: $(Build.Repository.Uri)
          inputs:
            targetType: 'inline'
            script: |
              echo "Cloning Target Branch: ${TARGET_BRANCH#refs/heads/}"

              # Clone the target branch
              git -c http.extraheader="Authorization: Bearer $ACCESS_TOKEN" \
              clone "$REPO_URL" --branch "${TARGET_BRANCH#refs/heads/}" --single-branch /tmp/target-branch

              echo "Cloning completed successfully!"

额外说明

  • 确保你的流水线确实是由PR触发的:pr: ['*']配置已经覆盖了所有PR触发场景,没问题。
  • System.AccessToken变量默认拥有仓库读取权限,足以完成克隆操作,无需额外配置权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:03:18