Is there a way to source
a shell script into a namespace, preferably a bash shell script but I would look into other shells if they had this feature and bash didn't.
What I mean by that is, e.g., something like "prefix all defined symbols with something so that they don't collide with already defined symbols (variable names, function names, aliases)" or any other facility that prevents name collisions.
If there's a solution where I can namespace at source
time (NodeJS
style), that would be the best.
Example code:
$ echo 'hi(){ echo Hello, world; }' > english.sh
$ echo 'hi(){ echo Ahoj, světe; }' > czech.sh
$ . english.sh
$ hi
#=> Hello, world
$ . czech.sh #bash doesn't even warn me that `hi` is being overwritten here
$ hi
#=> Ahoj, světe
#Can't use the English hi now
#And sourcing the appropriate file before each invocation wouldn't be very efficient
Best Answer
From
man ksh
on a system with aksh93
installed...And, to demonstrate, here is the concept applied to a namespace provided by default for every regular shell variable assigned in a
ksh93
shell. In the following example I will define adiscipline
function that will act as the assigned.get
method for the$PS1
shell variable. Every shell variable basically gets its own namespace with, at least, the defaultget
,set
,append
, andunset
methods. After defining the following function, any time the variable$PS1
is referenced in the shell, the output ofdate
will be drawn at the top of the screen...(Also note the lack of the
()
subshell in the above command substitution)Technically, namespaces and disciplines are not exactly the same thing (because disciplines can be defined to apply either globally or locally to a particular namespace), but they are both part and parcel to the conceptualization of shell data types which is fundamental to
ksh93
.To address your particular examples:
...or...