Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a script that is littered around my filesystem (side effect of a build process) that sets some global environment variables (LD_LIBRARY_PATH, PATH, ROOTDIR, etc) that need to be in my shell for proper operation. Of course, that means I need to source script.sh or . script.sh to get it to work, and not ./script.sh (which would spawn a new shell and not set the variables in my current shell).

Is there anything I can add to the script to prevent (or warn) someone running ./script.sh ?

share|improve this question
up vote 6 down vote accepted

In a shell script, $0 is the name of the currently running script. You can use this to tell if you're being sourced or run like this:

if [[ "$(basename -- "$0")" == "script.sh" ]]; then
    echo "Don't run $0, source it" >&2
    exit 1
fi
share|improve this answer

This has been discussed on SO. The most-upvoted answer by @barroyo says to use

[[ "${BASH_SOURCE[0]}" != "${0}" ]] && echo "script ${BASH_SOURCE[0]} is being sourced ..."
share|improve this answer
    
@will: The manual says: An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. How a function? – user Apr 18 at 14:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .