Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing bash output into a variable using eval

Tags:

bash

I have a line of code

eval echo \$$var 

which prints a string. How can I store this string into a variable?

like image 390
CocaCola Avatar asked Aug 12 '13 11:08

CocaCola


People also ask

How do you store the output of a command to a variable in a shell script?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

What does eval return bash?

Here, arguments are parsed and combined into a string that will execute by the shell. `eval` returns an exit status code after executing the command. `eval` returns 0 as exit status code if no argument is provided or only null argument is provided.

What is the use of eval in bash?

On Unix-like operating systems, eval is a builtin command of the Bash shell. It concatenates its arguments into a single string, joining the arguments with spaces, then executes that string as a bash command.


1 Answers

Like this:

eval c=\$$var 

a better, safer way is to use indirection:

c=${!var} 
like image 71
perreal Avatar answered Sep 25 '22 03:09

perreal