Was I Sourced?

Fabian Keil freebsd-listen at fabiankeil.de
Tue Feb 12 16:10:46 UTC 2013

"Teske, Devin" <Devin.Teske at fisglobal.com> wrote:

> On Tue, 12 Feb 2013, Tim Daneliuk wrote:
> > Is there a way for script to determine whether is was sourced
> > or forked off as a subprocess when it was invoked?
> > 
> Not that I'm aware of.

sysutils/zogftw, which has to find and parse itself to
generate the verbose help, does the following:


    if [ "zogftw" != $(basename "${zogftw_location}") ]; then
        # Looks like zogftw has been sourced.
        # Try to get the zogftw location through the PATH.
        zogftw_location="$(which zogftw)"

The check is expected to fail if the user renamed the shell to
zogftw, or the script to something else, but that's unlikely to
happen by accident and the functionality is not essential anyway.

A more reliable method might be investigating $$ and its parents
with ps and friends, but it would also require a lot more code.

I don't remember ever having never seen a ps-based check in the
real world and my impression is that looking at $0 is "best practice"
if the check doesn't have to be perfect.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20130212/74558050/attachment.sig>

More information about the freebsd-questions mailing list