Can I create an alias for a korn shell namespace?
Is there anything like the using directive in C++
(bring several namespaces together and throw a (compiler) error if a symbol designation is ambiguous)?

- 28,816
1 Answers
Even though ksh has more advanced feature than other shells, it's still at its heart a language to automate simple task and write small scripts, not a language geared towards writing huge applications. You can't expect to have all the features of a typical language designed for large applications, let alone all the features of C++.
I don't think you can create an alias for a namespace. You can create a copy of a namespace of sorts by enumerating its variables (parse the output of typeset +p
or typeset -p
, or use ${!.foo.*}
if you want to include variables inherited from the parent namespace) and copying them one by one. You can make a variable an alias of another with typeset -n
, but that only takes effect when used inside the namespace:
$ namespace foo { x=1; }
$ namespace bar { typeset -n x=.foo.x; echo $x; }
1
$ namespace foo { x=2; }
$ namespace bar { echo $x; }
2
$ echo ${.bar.x}
.foo.x
Ksh lets you go further and execute arbitrary code when a variable is read, modified or unset, with discipline functions. For example, if you define a function called x.get
, this function is invoked each time the value of x
is retrieved.
namespace bar {
x.get () { _=${.foo.x}; }
x.set () { .foo.x=${.sh.value}; }
x.append () { .foo.x+=${.sh.value}; }
x.unset () { unset ${.sh.name}; }
}
I think you have to define these for every variable, and you can't detect variables that are added to the namespace foo
.
This can be extended to look up multiple namespaces.
x.get () {
if ((${.foo.x+1}+${.bar.x+1}!=1)); then
echo 1>&2 "Ambiguous variable x, available in more than one of foo and bar"
exit 125
fi
_=${.foo.x-${.bar.x}}
}

- 829,060
-
I'll take a risk - but this is really good. It's just... have you looked at
typeset -T
? With-T
you can type - or template - a compound variable, which, as I think, could fill the gaps here. It's like a C struct. And you can use it to define your own disciplines. When you've defined a type you get a new builtin assignment command for it - and your subvariables (including disciplines) are copied over for each new instance you define with it. And all of that is not to mention thatksh
is extendable w/ C or C++ libs. – mikeserv Jul 06 '15 at 04:59
man
page and generally poking at the interface a little more to get an idea about how things work before asking specific questions about implementation details? It could be what you want and what you might want if you knew better are two very different things. At least, it usually works that way for me. – mikeserv Jul 05 '15 at 16:14