Bash: Detecting if Script is Sourced

Here is a quick way of detecting if your script is being source as part of a larger script or being executed directly:


#!/bin/sh

[ "$0" = "$(basename $SHELL)" ] && echo "Script is sourced"

And here are some tests:


ralph@goten:bin$ ./sourced.sh
ralph@goten:bin$ bash sourced.sh
ralph@goten:bin$ . sourced.sh
Script is sourced
ralph@goten:bin$ source sourced.sh
Script is sourced
ralph@goten:bin$



%d bloggers like this: