Skip to content

Instantly share code, notes, and snippets.

@mmulich
Created April 19, 2021 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmulich/03cce1f76bced3ec2c8a725e18bdc94a to your computer and use it in GitHub Desktop.
Save mmulich/03cce1f76bced3ec2c8a725e18bdc94a to your computer and use it in GitHub Desktop.
#!/bin/bash
script_name=$( basename ${0#-} ) #- needed if sourced no path
this_script=$( basename ${BASH_SOURCE} )
if [[ ${script_name} = ${this_script} ]] ; then
echo "running me directly"
else
echo "sourced from ${script_name}"
fi
echo '----------'
if [ "$(basename $0)" = "$(basename $BASH_SOURCE)" ]; then
echo "running directly"
else
echo "sourced from $0"
fi
echo '----------'
if [ ${#BASH_SOURCE[@]} -eq 1 ]; then echo "running directly"; else echo "sourced from $0"; fi
echo '----------'
# USE THIS ONE!
# check to see if this file is being run or sourced from another script
function _is_sourced() {
# See also https://unix.stackexchange.com/a/215279
# macos bash source check OR { linux shell check }
[[ "${#BASH_SOURCE[@]}" -eq 0 ]] || { [ "${#FUNCNAME[@]}" -ge 2 ] && [ "${FUNCNAME[0]}" = '_is_sourced' ] && [ "${FUNCNAME[1]}" = 'source' ]; }
}
if ! _is_sourced; then echo "direct"; else echo "sourced $0"; fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment