0

In python you can detect whether a script is executed as opposed imported by another script with this

if __name__ == '__main__':
    # We are run directly.

Is there a way in to do the same in a shell script? I have a couple of functions in script that I would like to be able to source, without executing them.

Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72

1 Answers1

1

So far I've come up with these:

if [ "$0" != "bash" ]
then
    # We are run directly because
    # $0 == our filename
    # Or is it? It could be a different shell!
fi

and

if [ "$(basename $0)" = "foo.sh" ]
then
    # We are run directly, because $0 == our filename.
    # But what if we get mv'ed to some other filename???
fi

Are there any less brittle solutions?

Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72