Reputation: 65
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
Upvotes: 0
Views: 327
Reputation: 65
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
Upvotes: 0
Reputation: 19982
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}"
Upvotes: 3
Reputation: 883
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
.
Upvotes: 0
Reputation: 103
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"\"'
Upvotes: 0