繁体   English   中英

重击:从变量名的字符串中获取变量的值(当字符串包含变量名以外的其他字符时)

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

给定此代码,它将打印“ abc _ $ {var1}”,但我希望它显示“ abc_def”,但是bash脚本有很多小细节,我不知道,因此希望有人可以解释此行为:

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}"

另一件事是,如果我直接从bash脚本返回(而不是调用Python),则可以得到所需的结果(但必须调用python)。 它与Python中的print返回与bash中的echo不同的字符串有关吗? 我什至不知道该如何检查。

需要明确的是,以下代码给出了理想的结果,尽管我不知道为什么但不能使用,因为我需要Python为我提供适当的值:

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}"

您如何为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

采用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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