Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookup shell variables by name, indirectly [duplicate]

Tags:

bash

eval

Let's say I have a variable's name stored in another variable:

myvar=123
varname=myvar

Now, I'd like to get 123 by just using $varname variable. Is there a direct way for that? I found no such bash builtin for lookup by name, so came up with this:

function var { v="\$$1"; eval "echo "$v; }

so

var $varname  # gives 123

Which doesn't look too bad in the end, but I'm wondering if I missed something more obvious.

like image 953
inger Avatar asked Nov 07 '09 19:11

inger


People also ask

How to see all environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

Can bash script access environment variables?

In Bash, environment variables define many different things : your default editor, your current username or the current timezone. Most importantly, environment variables can be used in Bash scripts in order to modify the behaviour of your scripts.

How do I find the value of an environment variable in Linux?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do you check variables in bash?

To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.


1 Answers

From the man page of bash:

${!varname}

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

like image 60
tangens Avatar answered Sep 24 '22 06:09

tangens