Dynamic variable names in Bash -
i confused bash script.
i have following code:
function grep_search() { magic_way_to_define_magic_variable_$1=`ls | tail -1` echo $magic_variable_$1 }
i want able create variable name containing first argument of command , bearing value of e.g. last line of ls
.
so illustrate want:
$ ls | tail -1 stack-overflow.txt $ grep_search() open_box stack-overflow.txt
so, how should define/declare $magic_way_to_define_magic_variable_$1
, how should call within script?
i have tried eval
, ${...}
, \$${...}
, still confused.
use associative array, command names keys.
# requires bash 4, though declare -a magic_variable=() function grep_search() { magic_variable[$1]=$( ls | tail -1 ) echo ${magic_variable[$1]} }
if can't use associative arrays (e.g., must support bash
3), can use declare
create dynamic variable names:
declare "magic_variable_$1=$(ls | tail -1)"
and use indirect parameter expansion access value.
var="magic_variable_$1" echo "${!var}"
Comments
Post a Comment