> Date: Tue, 13 Dec 2011 08:50:03 +0100
> From: [email protected]
> To: [email protected]; [email protected]
> Subject: Re: [ast-users] Is there a simple way for a script to know if it's 
> run as a script (ksh script ) or sourced (. script) ?
> CC:
>
> David Korn:
> > Since you are dotting script-b, shouldn't SHLVL remain the same.
> > If you instead run
> > ./script-b
> > instead, then the level should be one higher.
>
> Correct. But I wanted something that would work at any level.
>
> My conclusion is that I need to know the name of the script
> as it is being called and trigger on that. This allows me
> to put all of my code in functions and include one statement
> at the bottom:
>
> case $0 in
> (*/$myname) do_stuff $@
> esac
>
> Compare this with python:
>
> if __name__ == '__main__':
> actually_do_stuff(argv[1:])
>
>
> This trick/hack/convention allows the same file to be
> sourced/included/imported by another without having it come to action.
>
> This is useful both for (unit)testing and for code reuse using the same
> files.
>
> If we'd add a language feature, I'd suggest something like a special
> variable like '$<' or '$.' containing the name of the file containing
> the code that is running now, to distinguish it from the name of the
> current process ($0).

Another option could be to use the already existing built-in
variable $- and add (similar to "interactive" flag 'i') another
letter for sourced scripts.

Janis

>
> It's a bit late in the history of ksh, as it would not help existing
> code out there.
>
> ksh script.sh # should always reset both $0 *and* $.
> $0=.../script.sh
> $.=.../script.sh
>
> . script.sh # from a script called main.sh
> $0=.../main.sh
> $.=.../script.sh
>
> (where .../ would be the actual pathname prefix for the location of the
> file, using the same rules for both.)
>
>
> Cheers,
> Henk
> _______________________________________________
> ast-users mailing list
> [email protected]
> https://mailman.research.att.com/mailman/listinfo/ast-users
                                          
_______________________________________________
ast-users mailing list
[email protected]
https://mailman.research.att.com/mailman/listinfo/ast-users

Reply via email to