Quote:
Originally Posted by coolhandluke1
how does the argument string '${'"$envvar"'}' get converted to ${PATH}? I know it has something to do with evaluation order of the shell, however the books explanation of this subject is not detailed enough for me.
|
The shell variable
envvar has the value 'PATH'. So
$envvar is substituted ("expanded" in shell lingo) with
PATH.
'${' and '}' are just a literal strings. The single quotes prevent the shell from treating the
$ and the
{ as special character and trying to interpret them.
The double quotes prevents whitespace to be interpreted as seperators. And since PATH does not contain spaces, the double quotes are not really needed in this case. So this would also do it:
Code:
dirpath=$(eval echo '${'$envvar'}' 2>/dev/null | tr : ' ')
BTW,
$PATH does the same as
${PATH}. Only in some cases the curly brackets are needed. Not here. So this command would do the same (in this case):
Code:
dirpath=$(eval echo '$'$envvar 2>/dev/null | tr : ' ')
So a string
${PATH} is created by expanding the
envvar variable and we want that string expanded yet another time by the shell. This is done by the
eval command. This is some sort of trick to get the value of a variable, while the name of the variable itself is inside a variable. The bash shell has a special construction to do this. So if the shell is bash, this does the same as you original full example:
Code:
dirpath=$(echo ${!envvar} | tr : ' ')