bash - Bash 中的动态变量名称

标签 bash variables dynamic syntax

我对 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/45821583/

相关文章:

python - 使用 echo 写入文件的换行符在 shell 中有效,但在 Python 3 中为文字

java - 在 Java 中从变量声明新类

swift - 无法将类型“UITextField”与预期参数类型 ‘String’ 协调一致

c - 动态链接器如何更改进程的文本段?

javascript - 根据视口(viewport)高度及其位置自动计算div的高度

linux - 迭代 map 并导出变量

linux - 无法通过 SSH 保留最新的 5 个文件夹并删除较旧的文件夹

linux - 使用 AWK 合并文件中的相似行

C++:使用循环和变量模式(序列)

MySQL 使用另一个表中的列名