0

I need to make variable using two other variable values.

#i have two variable in unix i.e.#
v_a=a
v_b=b
##now i want to combine the two values of the two variable and the result of that i want that as a variable means v_a_b and use it.##
echo 'v_'$v_a'_'$v_b #the output will be v_a_b and i want to use it like $v_a_b
3
  • $v_a_b is a variable that i want to use further in my code. Commented Jun 14, 2016 at 6:11
  • What should be the value of $v_a_b? Did you check Walter's answer below? Commented Jun 14, 2016 at 14:16
  • you can give any value to $v_a_b i want to use this in further block of my code. Yeah with eval i can to this. Commented Jun 16, 2016 at 9:51

4 Answers 4

3

Suppose you have the following vars:

v_a=a
v_b=b
v_a_b="I want this one"
v_a_c="Wrong one!"

How do you get I want this one using the values of v_a and v_b ?
You can use eval, but try to avoid that:

# don't do this
eval echo "\$v_${v_a}_${v_b}"

You need a new variable , lets call it c and get the value of the constructed var:

c="v_${v_a}_${v_b}"
echo "Using the exclamation mark for retrieving the valueCombined: ${!c}"

Another way is using printf:

printf -v c "v_%s_%s" "${v_a}"  "${v_b}"
echo "Combined: ${!c}"
Sign up to request clarification or add additional context in comments.

Comments

0

Use eval to explicitly pre-evaluate an expression.
for your question,

eval 'echo \$v_"$v_a"_"$v_b"'

should work fine,
echo \$v_"$v_a"_"$v_b" evaluates to echo $v_a_b, then the intermediate result is evaluated again, so in effect, we get the result of $(echo $v_a_b) note: you might want to quote the variable $v_a_b:

eval 'echo \"\$v_"$v_a"_"$v_b"\"'

Comments

0

If I understand correctly, you want to concatenate the contents of variables v_a and v_b (along with some fixed strings 'v_' and '_') then store it in a variable named v_a_b.

v_a=a
v_b=b
v_a_b='v_'$a'_'$b
echo $v_a_b

The output is v_a_b.

1 Comment

no this i don't want to do. I want to make a new variable with the result of two variables and then use it like result will be v_a_b and i want to use $v_a_b.
0
   v_a=a
   v_b=b
   v_a_b=c
   eval V_XYZ='$'"v_"$v_a"_"$v_b
   echo 'Value= '$V_XYZ

output will be c

Comments

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.