巴什动态变量名 [英] Bash dynamic variable names
问题描述
我感到困惑的bash脚本。
I am confused about a bash script.
我有以下的code:
function grep_search() {
magic_way_to_define_magic_variable_$1=`ls | tail -1`
echo $magic_variable_$1
}
我希望能够创建一个包含命令的第一个参数和轴承例如值的变量名的 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?
我曾尝试评估
, $ {...}
, \\ $$ {...}
,但我仍然感到困惑。
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]}
}
如果您不能使用关联数组(例如,你必须支持庆典
3),可以使用声明
创建动态变量名:
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}"
这篇关于巴什动态变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!