Bash: detect execute vs source in a script?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Bash: Detect Execute Vs Source In A Script?
00:37 Accepted Answer Score 21
00:54 Answer 2 Score 4
01:08 Answer 3 Score 20
01:31 Answer 4 Score 1
01:40 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
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Bash: Detect Execute Vs Source In A Script?
00:37 Accepted Answer Score 21
00:54 Answer 2 Score 4
01:08 Answer 3 Score 20
01:31 Answer 4 Score 1
01:40 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.