2

Suppose:

a=b; b=c; c=d

Then eval echo \$$a produces the output:

c

If we want to extract the output d using just input a, I tried the following way:

(i) eval echo \$(eval echo \$$a) produces the error:

syntax error near unexpected token '('

(ii) eval echo \$\(eval echo \$$a\) produces the output:

c

I am not able to understand why escape slashing the bracket got rid of the error.

Also, could someone please explain why I didn't get the output as d in the second instance?

  • See Eval command and security issues – Wildcard Nov 10 '16 at 21:01
  • @Wildcard I am new to bash shell programming. The link which you provided is a bit tough to me. Could you please explain in simple words where I went wrong? – MathMan Nov 10 '16 at 21:05
  • Sure. From a security standpoint, it's a really bad idea to use eval in any shell script unless you know exactly what you're doing. (And even then, there are virtually zero instances where it is actually the best solution.) As a beginner to shell scripting, please just forget that eval even exists. :) – Wildcard Nov 10 '16 at 21:07
  • @Wildcard ohk.. I understand but I would be really grateful if you could pin point where I went wrong in my code. – MathMan Nov 10 '16 at 21:11
4

First, a word of caution:

From a security standpoint, it's a really bad idea to use eval in any shell script unless you know exactly what you're doing. (And even then, there are virtually zero instances where it is actually the best solution.) As a beginner to shell scripting, please just forget that eval even exists.

For further reading, see Eval command and security issues.


To get the output d, you could use:

eval echo \$${!a}

Or:

eval eval echo \\\$\$$a

Where you went wrong was in passing the unescaped parentheses characters to echo. If they are preceded by an unquoted $, it is command substitution. But if the $ is quoted and not the parentheses, it isn't valid shell syntax.

3

Nested evals are a messy thing.

First,

eval echo \$\(eval echo \$$a\)

causes the interpreter to evaluate the following:

echo $(eval echo $b)

Interpolating the innermost nested command (i.e. $(eval echo $b)) results in:

echo c

Which gives you the result:

c

If you want the nested evals to get evaluated correctly (and I highly recommend not using eval to at all), you have to get pretty weird. See other answers for examples.

  • Thanks. Could you also please explain why back slashing the parenthesis was important here – MathMan Nov 10 '16 at 21:48
1

You could get the expected output d with the following :

eval echo \$$(echo ${!a})

${!a} is a bash variable name expansion that gives c with your values. See bash manual.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.