Nice one.  (Just have to swap "sourced" and "subshell", see below)

Smart to go through the whole list of .sh.* variables.

Question to David and Glenn: When was .sh.file introduced?

Cheers,
Henk

$ cat cyril.sh
print file=${.sh.file} arg0=${0}

if [[ ${.sh.file##*/} = ${0##*/} ]]; then
         echo sourced
else
         echo subshell
fi
----------------------
$ ksh caller.sh
sourcing:
file=/home/Henk/src/ksh-tests/cyril.sh arg0=caller.sh
subshell

calling:
file=/home/Henk/src/ksh-tests/cyril.sh arg0=cyril.sh
sourced



On Wed, Jan 4, 2012, at 03:55 AM, Cyrille Lefevre wrote:
> Le 13/12/2011 08:50, Henk Langeveld a écrit :
> > 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.
> 
> test case :
> 
> $ cat so
> echo _=$_
> echo 0=$0
> for i in ${.sh[@]}; do nameref sh=.sh.$i; echo $i:$sh; done
> 
> $ cat sub
> . so
> 
> $ ksh93 so | egrep '^(0|file)'
> 0:so
> file:/tmp/so
> 
> $ ksh93 sub | egrep '^(0|file)'
> 0:sub
> file:/tmp/so
> 
> answer :
> 
> if [[ ${.sh.file##*/} = ${0##*/} ]]; then
>          echo sourced
> else
>          echo subshell
> fi
> 
> done ;^)
> 
> Regards,
> 
> Cyrille Lefevre
> -- 
> mailto:[email protected]
> 

_______________________________________________
ast-users mailing list
[email protected]
https://mailman.research.att.com/mailman/listinfo/ast-users

Reply via email to