0

I want to define the following:

COMMIT_ID_${ARCH}=$(git log --format="%H" -n 1)

But it fails:

-bash: COMMIT_ID_amd64=a7c9e0a53972a3d42a8035f45469f1959a0475f8: command not found

5
  • 3
    How will you reference your variable later? Because while you can use your dynamic variable with declare+indirect expansion, using associative arrays is generally simpler & more readable. Commented Oct 21, 2019 at 14:23
  • 1
    Unless you will have two variables like COMMIT_ID_x86 and COMMIT_ID_arm, there's nothing gained by defining COMMIT_ID_x86 instead of simply COMMIT_ID. Commented Oct 21, 2019 at 14:24
  • I will have two. I used echo $COMMIT_ID_${ARCH}. Commented Oct 21, 2019 at 14:32
  • I'm not actually echoing it as it is in a script and is used in a sed substitution. Commented Oct 21, 2019 at 14:33
  • All your questions about indirection are answered by BashFAQ/006 Commented Oct 21, 2019 at 14:33

2 Answers 2

2

Use an associative array.

declare -A commit_id

commit_id[$ARCH]=$(git log --format="%H" -n 1)

...

echo "${commit_id[$ARCH]}"
Sign up to request clarification or add additional context in comments.

3 Comments

It appears that the declaration does not persist across functions. Would you know how I can resolve this?
In a function, add the -g flag to the declare command to make the array a global variable.
I moved it outside the function and it worked but I think -g and keeping it within s better. Thanks for your assistance.
0

You can use declare directive for this:

declare "COMMIT_ID_${ARCH}"=$(git log --format="%H" -n 1)

To examine new variable use:

declare -p "COMMIT_ID_${ARCH}"

Based on comments below by OP:

# create your variable
var="COMMIT_ID_${ARCH}"

# set variable by calling git log
declare "$var"=$(git log --format="%H" -n 1)

# examine value of $var
echo "${!var}"

6 Comments

I tried this earlier but it did not return the correct value: echo $COMMIT_ID_${ARCH} returns amd64. I'd prefer not to have to run declare -p each time I want the actual value if possible. I'm not actually echoing it as it is in a script and is used in a sed substitution.
Clear explanation of declare usage, thank you. Unfortunately though it still leaves me with the problem of not having $ARCH ref in variable name as I will have amd64 & arm64v8 and need to differentiate between them.
You will have 2 different variables created COMMIT_ID_amd64 and COMMIT_ID_amd64v8 after above run.
Would they both not be called var?
var is just a temporary holder. Where and how are you going to use these 2 variables?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.