Bash: test whether script is invoked directly or sourced

If you have a Bash script that needs to be sourced (versus directly executed), you can enforce this by checking the execution context in the script.

Here is an example of setting a flag that can be evaluated and then acted upon.

(return 0 2>/dev/null) && sourced=1 || sourced=0
if [ $sourced -eq 0 ]; then
  echo "ERROR, this script is meant to be sourced."
  exit 1
fi

I have the full sample script on github.

The snippet above comes from a discussion by mklement0 on stackoverflow where solutions in multiple shell flavors are provided, and is more robust than another approach often used.

# not as robust as example above
[[ $0 != "$BASH_SOURCE" ]] && sourced=1 || sourced=0

 

REFERENCES

stackoverflow, how to detect if a script is being sourced