Can I substring a variable in Azure Pipelines?

My other approach would be to use a bash task and overwrite the variable there but finding something build-in that can do this would be way better solution.

I agree with Lucas. There is no such built-in task to get the first 7 characters of $(Build.SourceVersion) in Azure DevOps.

We could use the command line/powershell task to split long sha into short sha:

echo $(Build.SourceVersion)

set TestVar=$(Build.SourceVersion)

set MyCustomVar=%TestVar:~0,7%

echo %MyCustomVar%

echo ##vso[task.setvariable variable=ShortSourceVersion]%MyCustomVar%

In this case, we could get the short versions of Build.SourceVersion and set it as environment variable.

Then we could set this command line task as a task group:

enter image description here

So, we could use this task to set the ShortSourceVersion directly.

Hope this helps.


Here is the shortest version that I use for this job;

- bash: |
    longcommithash=$(Build.SourceVersion)
    echo "##vso[task.setvariable variable=shorthash;]$(echo ${longcommithash::9})"

It gives you the output as shown below;

enter image description here


You are right, there is no native way to do it. You will have to write a script to transform the variable.

Here is an example:

trigger:
- master

resources:
- repo: self

stages:
- stage: Build
  displayName: Build image
  jobs:  
  - job: Build
    displayName: Build
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: CmdLine@2
      inputs:
        script: ' x=`echo "$(Build.SourceVersion)" | head -c 7`; echo "##vso[task.setvariable variable=MyVar]$x"'
    - task: CmdLine@2
      inputs:
        script: 'echo "$(MyVar)"'