pir8
pir8

Reputation: 59

How can i get this value in this variable [Linux Bash]

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

Upvotes: 4

Views: 924

Answers (2)

glenn jackman
glenn jackman

Reputation: 246774

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]}"

Upvotes: 4

shellter
shellter

Reputation: 37268

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.

Upvotes: 3

Related Questions