4

Can i get this value in this variable [Linux Bash] my code

#!/bin/bash
COUNTER=1
"user$COUNTER"=text
echo "$user$COUNTER"

result : 1 i need result : text

2 Answers 2

4

In general, working with dynamic variable names like you want will only make your life more difficult. Arrays are much easier to work with (even in bash with it's picky syntax:

#!/bin/bash
counter=1
declare -a user   # this line is optional
user[$counter]=text
echo "${user[$counter]}"
Sign up to request clarification or add additional context in comments.

Comments

3

The trick is eval

eval user$COUNTER=text

Output:

/home/shellter:>eval "user$COUNTER"=text
/home/shellter:>echo $user1
text

Eval performs variable evaluations any visible variables on the command line, and then 'resubmits' the results to normal command-line evaluation and processing.

You can see some of this happening (once you have worked with for a while it will become obvious) by turning on the shell debugging with set -vx.

I hope this helps.

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

1 Comment

You also need to eval echo $user$COUNTER -- you have to eval any time you want to dereference the "compound" variable.

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.