Home > Back-end >  Bash : improve variable indirection assignment in one line
Bash : improve variable indirection assignment in one line

Time:12-04

In my Gitlab project, I set the Gitlab variables MY_VAR_DEV and MY_VAR_PROD.

Depending on the commit branch, I want a different behavior on the CI/CD pipeline (.gitlab-ci.yml file), according to the below code:

- if [ $CI_COMMIT_BRANCH == "dev" ]; then export ENV="DEV"; fi
- if [ $CI_COMMIT_BRANCH == "prod" ]; then export ENV="PROD"; fi
- TMP_MY_VAR="MY_VAR_${ENV}"
- export MY_VAR=$( eval echo \$$TMP_MY_VAR )
#- ... bla bla with $MY_VAR use

Is there a way to merge the last 2 lines and directly affect to MY_VAR the value of the evaluation of the MY_VAR_${ENV} ? (I mean no use of TMP_MY_VAR)

Thank you for your help :)

CodePudding user response:

This isn't an indirect assignment, it's an indirect dereference. Assuming bash 4.x:

# append all-caps version of CI_COMMIT_BRANCH contents to MY_VAR_prefix
var="MY_VAR_${CI_COMMIT_BRANCH^^}"

# dereference variable created above, assign result to MY_VAR
MY_VAR=${!var}

...and of course, you can make the whole thing one line:

var="MY_VAR_${CI_COMMIT_BRANCH^^}"; MY_VAR=${!var}

CodePudding user response:

There's something to be said for repeating yourself a little.

- if [ "$CI_COMMIT_BRANCH" = "dev" ]; then MY_VAR=$MY_VAR_DEV; fi
- if [ "$CI_COMMIT_BRANCH" = "prod" ]; then MY_VAR=$MY_VAR_PROD; fi
- export MY_VAR
#- ... bla bla with $MY_VAR use

or

- case $CI_COMMIT_BRANCH in dev) MY_VAR=$MY_VAR_DEV ;; prod) MY_VAR=$MY_VAR_PROD ;; esac
- export MY_VAR

There's no need to complicate matters with indirect parameter expansion, especially if you are using a shell that doesn't support it without extremely fragile uses of eval.

(Unless MY_VAR is used by another program executed by your shell, it doesn't need to be exported.)

  • Related