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