1

I am trying to substitute a variable inside another variable in shell script. but its showing as empty string. Below is the scenario.

  1. Assigning "x" with string containing variable "abc"
~$ x="new value is \${abc}"
~$ echo $x
new value is ${abc}
  1. Below is content of script abc.sh, defining the value of abc->
#!/bin/bash
abc="something='123:234'"
xyz=$@
echo $xyz
  1. When executing command "sh abc.sh $x" getting below value.

actual -> new value is ${abc}

expected - > new value is something='123:234'

Please help solving above issue.

Thanks

0

As you insert the value new value is ${abc}, the ${abc} part is just a string of characters. This string is not reevaluated for expansions when you do xyz=$@.

To expand ${abc} in the string, do the following in the script:

abc="something='123:234'"

eval "xyz=\"$1\""

printf '%s\n' "$xyz"

The eval takes a piece of shell code. The given code does xyz="$1", but with $1 replaced by the command line argument (the string new value is ${abc}). This statement is then reevaluated by the shell, assigning the correct string to the variable.

  • Thanks for quick response @Kusalananda. Is there any other way where I dont need to edit the script and with some changes in variable "x" itself, results can be achieved. – RDP Oct 24 '19 at 15:50
  • @RDP No, there is not. – Kusalananda Oct 24 '19 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.