Home > other >  Get branch name without path and set as variable
Get branch name without path and set as variable

Time:06-18

I have a Command Line Script task in a Azure pipeline job. Within the script I have the following:

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

In theory, this should set refs/heads/branchName to the $branchSource variable. Then we replace refs/heads/ with empty space/nothing, then storing whats left i.e:branchName in the $branchSourcePath.

The issue I get when the pipeline runs, is this in the console - referring to the lines above:

/Users/myagent/path/*******-********.sh: line 2: =: command not found
/Users/myagent/path/*******-********.sh: line 3: =: command not found

If I echo "$(System.PullRequest.SourceBranch)" in my script, it displays it fine as a path. How can I get just the branch name stored in a variable.

Thanks in advance.

CodePudding user response:

/Users/myagent/path/*******-********.sh: line 2: =: command not found

From the error message, the task is using bash script. You command is suitable for PowerShell task.

You can change to use PowerShell task.

Or you can change to use Bash Script:

Here is an example:

BRANCH_NAME=$(echo "$(System.PullRequest.SourceBranch)" | awk -F/ '{print $NF}')

echo $BRANCH_NAME
echo "##vso[task.setvariable variable=PullRequest_Source_Branch;]$BRANCH_NAME"
  • Related