BASH 使用双变量 $ - 错误替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21156136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:16:11  来源:igfitidea点击:

BASH using double variable $ - bad substitution

bashvariablessubstitution

提问by adiwhy

From my code below, how to make the value of 'zz' become 500 after replacing 'critical_' with x on variable 'yy'

从我下面的代码中,如何在变量 'yy' 上用 x 替换 'critical_' 后使 'zz' 的值变为 500

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

谢谢阿迪

回答by anubhava

May be like this:

可能是这样的:

xab123=500
yy="critical_ab123"
zz="${yy//critical_/x}"
echo ${!zz}
500

回答by Stephen Quan

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.

一个有趣的用法是,当您调用 bash 函数时,您可以对传入的参数使用间接。然后,您可以使用命令替换以嵌套方式嵌套对间接函数的调用。

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 derefused to solve the OP's problem:

这里deref用于解决OP的问题:

deref() { echo "${!1}"; }

xab123="500"
yy="critical_ab123"
zz="$(deref "${yy//critical_/x}")"

echo "$zz" # Outputs: 500

Applied edits based on @charles-duffy comments:

基于@charles-duffy 评论的应用编辑:

  1. Disclaimer: reader beware, there are performance impacts to the command substitution used in this approach (FIFO creation, fork() of a subshell, read() and wait().
  2. Quotes were added to protect against lossy expansion, i.e. echo "$zz"is better than echo $zz
  3. Use POSIX-compliant function declaration syntax, i.e. replaced function deref { echo "${!1}" ; }with deref() { echo "${!1}" ; }
  4. Corrected quoting issue for each quoting context
  1. 免责声明:读者请注意,此方法中使用的命令替换会影响性能(FIFO 创建、子 shell 的 fork()、read() 和 wait())。
  2. 添加了引号以防止有损扩展,即echo "$zz"优于echo $zz
  3. 使用符合 POSIX 的函数声明语法,即替换function deref { echo "${!1}" ; }deref() { echo "${!1}" ; }
  4. 更正每个引用上下文的引用问题