Bash中的动态变量名称 [英] Dynamic variable names in Bash

查看:93
本文介绍了Bash中的动态变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash脚本感到困惑.

I am confused about a bash script.

我有以下代码:

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

我希望能够创建一个变量名称,该变量名称包含命令的第一个参数,并带有例如ls的最后一行.

I want to be able to create a variable name containing the first argument of the command and bearing the value of e.g. the last line of ls.

为了说明我想要的东西:

So to illustrate what I want:

$ ls | tail -1
stack-overflow.txt

$ grep_search() open_box
stack-overflow.txt

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

So, how should I define/declare $magic_way_to_define_magic_variable_$1 and how should I call it within the script?

我尝试过eval${...}\$${...},但我仍然感到困惑.

I have tried eval, ${...}, \$${...}, but I am still confused.

推荐答案

使用关联数组,命令名称作为键.

Use an associative array, with command names as keys.

# Requires bash 4, though
declare -A magic_variable=()

function grep_search() {
    magic_variable[$1]=$( ls | tail -1 )
    echo ${magic_variable[$1]}
}

如果您不能使用关联数组(例如,您必须支持bash 3),则可以使用declare创建动态变量名称:

If you can't use associative arrays (e.g., you must support bash 3), you can use declare to create dynamic variable names:

declare "magic_variable_$1=$(ls | tail -1)"

并使用间接参数扩展来访问该值.

and use indirect parameter expansion to access the value.

var="magic_variable_$1"
echo "${!var}"

请参阅BashFAQ:间接-评估间接/引用变量.

See BashFAQ: Indirection - Evaluating indirect/reference variables.

这篇关于Bash中的动态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆