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

#1

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?

#2

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.

#3

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

#4

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
#5

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: https://circleci.com/docs/2.0/env-vars/#using-bash_env-to-set-environment-variables

closed #6

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