How to define a variable as a substring of another variable?

I would like to add a command that uses a substring of another variable.

$MY_VARIABLE is set to first/second. I want to only use everything after the / slash symbol, and either add this to a new variable, or use the result in another command.

How do I take a substring of that environment variable?

It depends on where in the YAML config you are wanting to do this. If it is a run step where you can use arbitrary shell commands, I expect you can do substring operations using awk.

Thanks for your help.

I tried this, where $MY_VARIABLE is set to first/second, but I only want the second part after the slash symbol.

  - run:
      name: Set variable
      command: $VARIABLE=$(echo $MY_VARIABLE  | cut -d '/' -f 1)

However, this returns the result: /bin/sh: =circleci: not found

Could you try this instead, with backticks?

VARIABLE=`echo $MY_VARIABLE  | cut -d '/' -f 1`

Also, to set a variable, you don’t need the dollar symbol.

1 Like

Please note that settings this variable will not persist across steps. Each step runs in a separate shell.

You should use the $BASH_ENV approach instead:

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.