[PLUG] bash question

Denis Heidtmann denis.heidtmann at gmail.com
Sat Apr 3 15:31:27 UTC 2010


On Sat, Apr 3, 2010 at 8:18 AM, David Fleck <david.fleck at mchsi.com> wrote:

> On Fri, 2 Apr 2010, Denis Heidtmann wrote:
> > Is there a way for my script to detect that it is sourced rather than
> > executed?
>
> I can think of a few tests, but since none of my machines have dash, I
> can't guarantee they will work....
>
> You can write the name of the script into a variable, and compare that
> with the value of '$0'.  If they match, then the script was executed; if
> not, it was sourced:
>
> #!/bin/sh
> . $HOME/script1.sh full
> . ./script1.sh relative
>
> sh $HOME/script1.sh exec
>
>
> #! /bin/sh
> self=script1.sh
> called=`basename $0`
>
> if [ "$self" != "$called" ]; then
>         echo "I am sourced: $@"
> else
>         echo "I am executed: $@"
> fi
>
>
> ]$ sh script2.sh
> I am sourced: full
> I am sourced: relative
> I am executed: exec
>
>
> Your problem sounds like a bug in dash.
>
> --
> David Fleck
> david.fleck at mchsi.com


Neat!  I will give it a try.  If it works in dash, it will solve my problem
quite neatly.  I do not know if my problem is a dash bug or a feature.

-Denis



More information about the PLUG mailing list