gpt4 book ai didi

bash - Bash 中的动态变量名称

转载 作者:行者123 更新时间:2023-11-29 08:38:25 25 4
gpt4 key购买 nike

我对 bash 脚本感到困惑。

我有以下代码:

function grep_search() {
magic_way_to_define_magic_variable_$1=`ls | tail -1`
echo $magic_variable_$1
}

我希望能够创建一个变量名,其中包含命令的第一个参数并承载例如ls 的最后一行。

所以为了说明我想要什么:

$ ls | tail -1
stack-overflow.txt

$ grep_search() open_box
stack-overflow.txt

那么,我应该如何定义/声明 $magic_way_to_define_magic_variable_$1 以及我应该如何在脚本中调用它?

我试过eval${...}\$${...},但还是一头雾水.

最佳答案

我最近一直在寻找更好的方法。关联数组对我来说听起来有点矫枉过正。看看我发现了什么:

suffix=bzz
declare prefix_$suffix=mystr

……然后……

varname=prefix_$suffix
echo ${!varname}

来自docs :

The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. ...

The basic form of parameter expansion is ${parameter}. The value of parameter is substituted. ...

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion. The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. ...

关于bash - Bash 中的动态变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16553089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com