Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

% PATH="MYPATH"
% VAR="PATH"

% echo $(eval echo \$$VAR)
MYPATH

% echo `eval echo \$$VAR`
5707VAR
 ^^
This is the process number.

I thought those two were exactly the same, but obviously there are some differences, like escaping behavior. What are the differences?

share|improve this question

marked as duplicate by manatwork, Ulrich Dangel, vonbrand, Renan, rahmu Mar 15 '13 at 14:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
The second should read echo `eval echo \$$VAR` (the () introduces an extra shell in your example). But yes, it works as you say. –  vonbrand Mar 15 '13 at 12:01
    
BTW, you should write it: eval 'echo "${'"$VAR"'}"' or eval "echo \"\${$VAR}\"" –  Stéphane Chazelas Mar 15 '13 at 12:49
    
This is so silly. –  Profpatsch Mar 15 '13 at 12:58

1 Answer 1

up vote 6 down vote accepted

I will reproduced the text of BASH reference manual because I will not express it any better:

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by ‘$’, ‘`’, or ‘\’. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

Source: Bash reference manual, Command substitution

share|improve this answer
3  
To get the expected output, you have to escape the backslash with another backslash in backquotes: echo `eval echo \\$$VAR` –  choroba Mar 15 '13 at 11:41
1  
Or you simply use the other form ;-) there are many approaches to one problem: xkcd.com/399 –  Huygens Mar 15 '13 at 11:45
    
So is there any possible situation where you would prefer `` over $()? Up until now I actually prefered ` over $() since it is faster to type on Neo and doesn’t clutter the code as much. But with that escaping stuff… –  Profpatsch Mar 15 '13 at 13:05
    
@Profpatsch I cannot think of any useful or applicable example right now. –  Huygens Mar 15 '13 at 13:44

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