variable expansion in bash
Im reading a book on shell scripting and an example is given:
***FULL EXAMPLE*** # $envvar = PATH dirpath=$(eval echo '${'"$envvar"'}' 2>/dev/null | tr : ' ') ***SPECIFIC PART I DONT UNDERSTAND*** # $envvar = PATH echo '${'"$envvar"'}' this prints: ${PATH} What i am needing help understanding is: 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. Thanks in advance |
Quote:
'${' 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 : ' ') Code:
dirpath=$(eval echo '$'$envvar 2>/dev/null | tr : ' ') Code:
dirpath=$(echo ${!envvar} | tr : ' ') |
Looks like a slight typo to me. Try it like this:
Code:
#!/bin/bash sh ./tryit.sh /usr/local/bin /usr/bin /bin /usr/X11R6/bin /usr/games /usr/lib/java/bin /usr/lib/java/jre/bin /usr/lib/qt/bin . You should use the CODE tags when posting code so we can read it accurately. |
Quote:
|
The whole sequence prints the contents of the Environment Variable "PATH" w/ the colons changed to spaces. For some reason, it's using indirection (the value of the variable envvar, is the name of the variable PATH; & so the indirect value of envvar is the value of PATH). Why the author did not just use straight bash indirect expansion, I don't know. The following produces the same result:
Code:
envvar=PATH |
All times are GMT -5. The time now is 09:22 PM. |