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.
Use an associative array, with command names as keys.
If you can't use associative arrays (e.g., you must support
bash
3), you can usedeclare
to create dynamic variable names:and use indirect parameter expansion to access the value.
See BashFAQ: Indirection - Evaluating indirect/reference variables.
For indexed arrays, you can reference them like so:
Associative arrays can be referenced similarly but need the
-A
switch ondeclare
instead of-a
.Example below returns value of $name_of_var
As per BashFAQ/006, you can use
read
with here string syntax for assigning indirect variables:Usage:
I've been looking for better way of doing it recently. Associative array sounded like overkill for me. Look what I found:
...and then...
Wow, most of the syntax is horrible! Here is one solution with some simpler syntax if you need to indirectly reference arrays:
For simpler use cases I recommend the syntax described in the Advanced Bash-Scripting Guide.