Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

up vote 4 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
share|improve this answer
I needed to add a X prefix, i.e. [[ "$(basename "X$0")" == "script.sh" ]], otherwise $0 expanded to -bash when sourced which was a syntax error. –  thebjorn Nov 18 '14 at 11:34
Indeed, thanks. I fixed it by adding '--'. –  Mikel Nov 18 '14 at 16:51
That makes more sense (I always forget about the --..) –  thebjorn Nov 18 '14 at 18:32

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.