I have next:
$ export A=1
$ eval "echo $A; echo $A; lll; echo $?"
The output is:
1
1
-bash: lll: command not found
0
I don't know why I cannot get the exit code of lll
, and I happen to try next:
$ export A=1
$ eval "echo $A; echo $A; lll; echo \$?"
1
1
-bash: lll: command not found
127
You can see above works, meanwhile next also work:
$ export A=1
$ eval "echo \$A; echo \$A; lll; echo \$?"
1
1
-bash: lll: command not found
127
I wonder, why I had to add one \
before $?
? Also, why \
before $A
is not a must?
Remember that, because you have embraced the whole expression to be evaluated, in double quotes. This means that all parameters inside it will be expanded, before eval
is invoked. If you don't escape $?
, the parameters to be expanded are A
and ?
. You get the value of A
before eval
is run (which is what you want), but you would also get the value of ?
before eval
is run (which is not what you want). The backslash causes a literal $
to be passed to eval
, hence defering the time of calculating the status code.