May be like this:
xab123=500
yy="critical_ab123"
zz="${yy//critical_/x}"
echo ${!zz}
500
Question
From my code below, how to make the value of 'zz' become 500 after replacing 'critical_' with x on variable 'yy'
xab123=500
yy="critical_ab123"
zz=${"${yy//critical_/x}"}
echo $zz
instead the result, there is an error:
line 8: ${"${yy//critical_/x}"}: bad substitution
thanks adi
Solution
May be like this:
xab123=500
yy="critical_ab123"
zz="${yy//critical_/x}"
echo ${!zz}
500
OTHER TIPS
An interesting usage is when you call a bash function, you can use indirection on the parameters passed in. Then, you can nest calls to your indirection function in a nested manner using command substitution.
deref() { echo "${!1}"; }
aa="bb"
bb="cc"
cc="hello"
echo "$(deref aa)" # bb
echo "$(deref "$(deref aa)")" # cc
echo "$(deref "$(deref "$(deref aa)")")" # hello
Here's deref
used to solve the OP's problem:
deref() { echo "${!1}"; }
xab123="500"
yy="critical_ab123"
zz="$(deref "${yy//critical_/x}")"
echo "$zz" # Outputs: 500
Applied edits based on @charles-duffy comments:
echo "$zz"
is better than echo $zz
function deref { echo "${!1}" ; }
with deref() { echo "${!1}" ; }