Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # from another shell script
- source myScript.sh
- # from command prompt, or another shell script
- ./myScript.sh
- some_function() {
- # ...
- }
- if [ -z "$IS_SOURCED" ]; then
- some_function;
- fi
- $ cat example.sh
- #!/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
- $ cat example2.sh
- #!/bin/bash
- . ./example.sh
- $ ./example.sh
- running me directly
- $ ./example2.sh
- example.sh sourced from example2.sh
- function isSourced () {
- [[ "${FUNCNAME[1]}" == "source" ]] && return 0
- return 1
- }
- local _top_of_stack=$(( ${#FUNCNAME[@]} - 1 ))
- function inspFnStack () {
- local T+=" "
- local _at=
- local _text="n"
- local _top=$(inspFnStackTop)
- local _fn=${FUNCNAME[1]}; [[ $_fn =~ source|main ]] || _fn+="()"
- local i=_top; ((--i))
- #
- _text+="$i item function call stack for $_fn ...n"
- _text+="| L BASH_SOURCE{BASH_LINENO called from}.FUNCNAME n"
- _text+="| ---------------------------------------------------n"
- while (( $i > 0 ))
- do
- _text+="| $i ${T}$(inspFnStackItem $i)n"
- T+=" "
- ((--i))
- done
- #
- printf "$_textn"
- #
- return 0
- }
- function inspFnStackItem () {
- local _i=$1
- local _fn=${FUNCNAME[$_i]}; [[ $_fn =~ source|main ]] || _fn+="()"
- local _at="${BASH_LINENO[$_i-1]}"; [[ $_at == 1 ]] && _at="trap"
- local _item="${BASH_SOURCE[$_i]}{${_at}}.$_fn"
- #
- printf "%s" "$_item"
- return 0
- }
- function inspFnStackTop () {
- # top stack item is 1 less than length of FUNCNAME array stack
- printf "%dn" $(( ${#FUNCNAME[@]} - 1 ))
- #
- return 0
- }
- $ . sourced.sh
- bash
- $ source sourced.sh
- bash
- $ chmod +x sourced.sh
- $ ./sourced.sh
- ./sourced.sh
- $ cat ./sourced.sh
- echo $0
Add Comment
Please, Sign In to add comment