How to get a branch name with a slash in Azure DevOps?

When you build on a PR, you could use System.PullRequest.SourceBranch and System.PullRequest.TargetBranch variables.

System.PullRequest.TargetBranch

The branch that is the target of a pull request. For example: refs/heads/master. This variable is initialized only if the build ran because of a Git PR affected by a branch policy.

Use Predefined Build Variables

Besides, you could also define your own variable based on your needs if you want to use full or short path.

Just create a bash script that assigns the shorter branch name to a variable.

# Bash script
BRANCH_NAME=$(echo "$(System.PullRequest.TargetBranch)" | awk -F/ '{print $NF}')
echo "##vso[task.setvariable variable=PullRequest_Target_Branch;]$BRANCH_NAME"

Then you could reference $(PullRequest_Target_Branch) in your pipeline later.


I always use Build.SourceBranch in my scripts. Just assign it to a new variable and remove refs/heads/ from the start. I use only for CI and PR:

  1. For CI. I use Build.SourceBranch variable without refs/heads. I work with PowerShell:

$branchSource = "$(Build.SourceBranch)"
$branchSourcePath = $branchSource -replace "refs/heads/", ""

  1. For PRs. I use System.PullRequest.SourceBranch variable without refs/heads because Build.SourceBranch contains the path to the remote PR. The replacement is the same as in the first option just use the right variable.

$branchSource = "$(System.PullRequest.SourceBranch)"
$branchSourcePath = $branchSource -replace "refs/heads/", ""