Dynamic variable names in Bash

Konstantinos picture Konstantinos · May 14, 2013 · Viewed 202.3k times · Source

I am confused about a bash script.

I have the following code:

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

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

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.

Answer

Yorik.sar picture Yorik.sar · Aug 8, 2013

I've been looking for better way of doing it recently. Associative array sounded like overkill for me. Look what I found:

suffix=bzz
declare prefix_$suffix=mystr

...and then...

varname=prefix_$suffix
echo ${!varname}