The Computer Oracle

Bash: detect execute vs source in a script?

--------------------------------------------------
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:52 Accepted answer (Score 19)
01:12 Answer 2 (Score 19)
01:42 Answer 3 (Score 4)
02:01 Answer 4 (Score 1)
02:24 Thank you

--

Full question
https://superuser.com/questions/731425/b...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#bash

#avk47



ACCEPTED ANSWER

Score 21


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
    >&2 echo "Don't run $0, source it"
    exit 1
fi



ANSWER 2

Score 20


Simplest way in bash is:

if [ "$0" = "$BASH_SOURCE" ]; then
    echo "Error: Script must be sourced"
    exit 1
fi

$BASH_SOURCE always contains the name/path of the script.

$0 only contains the name/path of the script when NOT sourced.

So when they match, that means the script was NOT sourced.




ANSWER 3

Score 4


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 ..."



ANSWER 4

Score 1


Another option may be to remove execute permissions. In that case it can not be executed but it can still be sourced.