0

I'm using gitlab-ci and i wanna package my artifact with specified VERSION which exported by previous stages, but the key of version value is generated with CI_COMMIT_SHORT_SHA, and i export it like this:

export COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION=${VERSION}

but i can't use it like

echo ${COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION}

or

 `echo '$COMMIT_'"${CI_COMMIT_SHORT_SHA}"'_REVISION'`

any suggestions?

carl
  • 41
  • 5
  • `echo "COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION"`? – Cyrus Oct 13 '20 at 04:37
  • @Cyrus that will out put "COMMIT_something_VERSION", but i want use this string as a key of value – carl Oct 13 '20 at 04:46
  • Does this answer your question? [How to use a variable's value as another variable's name in bash](https://stackoverflow.com/questions/9714902/how-to-use-a-variables-value-as-another-variables-name-in-bash), in particular the answer given by Flimm. – user1934428 Oct 13 '20 at 05:00

1 Answers1

0

Hope below example help you:

$ foo=testvar

$ bar=testvalue

$ declare "someprefix_${foo}=${bar}"

# your variable
$ echo $someprefix_testvar
testvalue

# one way
$ eval echo '$'"someprefix_${foo}"
testvalue

# other way -  prints the contents of the real variable
$ out="someprefix_${foo}"
$ echo ${!out}
testvalue

eval : Execute arguments as a shell command.

declare : declare is a bash built-in command that allows you to update attributes applied to variables within the scope of your shell.

Refer : http://mywiki.wooledge.org/BashFAQ/006#Indirection

You need:

$ declare  "COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION=${VERSION}"
$ out="COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION"
$ echo ${!out}

Test Results:

[akshay@db1 tmp]$ CI_COMMIT_SHORT_SHA=abcdef
[akshay@db1 tmp]$ VERSION=1.2.0
[akshay@db1 tmp]$ declare  "COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION=${VERSION}"
[akshay@db1 tmp]$ out="COMMIT_${CI_COMMIT_SHORT_SHA}_VERSION"
[akshay@db1 tmp]$ echo ${!out}
1.2.0
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36