Bash 中的动态变量名 [英] Dynamic variable names in 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
.
为了说明我想要什么:
$ 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屋!