Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Making a script 'sourceable'



On Sat, 4 Sep 2004, DervishD wrote:

> > >     The second thing is derived from the above question: since
> > > checking for 'sourcery' ;) is very difficult even non portably, I've
> > > thought about making my zsh scripts sourceables.
> > Lloyd Z. has the way of it.
>     Well, an extra fork... I don't really like that method, but...

There's also this, wherein a function name unlikely to exist in the 
calling shell is invented and then that function destroys itself as soon 
as it is invoked:

--- 8< ---
#! bin/zsh
function __the_real_script_$$ {
  unfunction __the_real_script_$$
  emulate -LR zsh
  # body of script goes here, using "local" to control variables
}
__the_real_script_$$ "$@"
--- >8 ---

However, that pretty thoroughly demolishes the usefulness of $0, and any 
error messages that are printed will fail to show the name of the script 
and the line numbers will be "wrong".

On the other hand this (and the subshell wrapper variant, too) has the 
advantage that the entire script is parsed for syntax before any of it is 
executed, so if you make a mistake somewhere you don't have half-finished
script processing to clean up.

Back on the first hand again, though, you pay the memory cost of that 
parse on every call to the script.



Messages sorted by: Reverse Date, Date, Thread, Author