Anyone knows why the following function does not work in ksh (it does in bash)?
var() # Displays var value; case insensitive
{
_var="$1"
if [ -n "${!_var}" ] ; then
echo ${!_var}
else
_var=$(echo "$_var" | tr 'a-z' 'A-Z')
echo ${!_var}
fi
unset _var
}
$ var home
ksh: "${!_var}": 0403-011 The specified substitution is not valid for this command.
$ var path
/usr/local/bin:/usr/bin:/bin:/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS:/cygdrive/c/WINDOWS/System32/Wbem:/cygdrive/c/Program Files/Support Tools:/cygdrive/c/Program Files/Hummingbird/Connectivity/7.11/Accessories/
Thanks!
Vic.
Not exactly sure, what ${!_var} does in Bash, but if you are just looking to get the value of a variable in ksh, you should use ${var}
I'm not trying to get the value of the variable, but use the value as a variable name.
Here's the difference:
BASH
$ _var=HOME
$ echo ${_var}
HOME
$ echo ${!_var}
/home/VMendonc
KORN
$ _var=HOME
$ echo ${_var}
HOME
$ echo ${!_var}
ksh: ${!_var}: 0403-011 The specified substitution is not valid for this command.
oh sorry... overlooked the reference to a variable there.
There is no direct way of accessing a variable using name reference in ksh. You need to use eval to do that:
> var="This is a variable"
> _var=var
> echo $_var
var
> eval echo \$$_var
This is a variable
If you use ksh93, however, there is a way to create name references:
> /bin/ksh93 ## Start a ksh93 shell
> var="This is a variable"
> typeset -n _var=var
> echo $_var
This is a variable
"typeset -n" creates a nameref to the given variable in ksh93, but this feature is not available in ksh (i.e., ksh88)
And if using a nameref in ksh93, ! is used to produce the actual reference:
$ nameref _var=HOME
$ echo $_var
/home/user
$ echo ${!_var}
HOME