简体   繁体   中英

Bash: Get value of variable from string of variable name (when string contains other characters than variable name)

Given this code, it prints "abc_${var1}" but I want it to print "abc_def" but bash scripting has a lot of little details that I'm not aware of so hopefully someone can explain this behavior:

Shell scripts:

function main()
  var1="def"
  var2=$(get_val_sh ${another_var})

  echo ${var2}
  # I want to echo:
  #   abc_def
  # instead, I get:
  #   abc_${var1}


function get_val_sh()
  var3=call_python(get_val_py())
  echo ${var3}


Python:

def get_val_py():
  print "abc_${var1}"

The other thing is that if I directly return from a bash script (rather than calling Python), I do get the desired result (but I have to call python). Does it have something to do with print in Python returning a different kind of string than echo in bash? I don't even know how to check this.

To be clear, the following code gives the desired result though I have no idea why but can't be used because I need Python to give me the appropriate value:

function main()
  var1="def"
  var2=$(get_val_sh ${another_var})

  echo ${var2}
  # I want to echo:
  #   abc_def
  # instead, I get:
  #   abc_${var1}


function get_val_sh()
  echo "abc_${var1}"

How are you assigning value to var2?

var1="def"
var3="var1" # var3 contains name of the variable. Note: NOT $var1
var2="abc_${var3}" # This will give abc_var1, not abc_def

Use

var2="abc_${!var3}" # This should give abc_def

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM