Guest User

Untitled

a guest
Feb 17th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. # from another shell script
  2. source myScript.sh
  3.  
  4. # from command prompt, or another shell script
  5. ./myScript.sh
  6.  
  7. some_function() {
  8. # ...
  9. }
  10. if [ -z "$IS_SOURCED" ]; then
  11. some_function;
  12. fi
  13.  
  14. $ cat example.sh
  15. #!/bin/bash
  16. script_name=$( basename ${0#-} ) #- needed if sourced no path
  17. this_script=$( basename ${BASH_SOURCE} )
  18. if [[ ${script_name} = ${this_script} ]] ; then
  19. echo "running me directly"
  20. else
  21. echo "sourced from ${script_name}"
  22. fi
  23.  
  24. $ cat example2.sh
  25. #!/bin/bash
  26. . ./example.sh
  27.  
  28. $ ./example.sh
  29. running me directly
  30. $ ./example2.sh
  31. example.sh sourced from example2.sh
  32.  
  33. function isSourced () {
  34. [[ "${FUNCNAME[1]}" == "source" ]] && return 0
  35. return 1
  36. }
  37.  
  38. local _top_of_stack=$(( ${#FUNCNAME[@]} - 1 ))
  39.  
  40. function inspFnStack () {
  41. local T+=" "
  42. local _at=
  43. local _text="n"
  44. local _top=$(inspFnStackTop)
  45. local _fn=${FUNCNAME[1]}; [[ $_fn =~ source|main ]] || _fn+="()"
  46. local i=_top; ((--i))
  47. #
  48. _text+="$i item function call stack for $_fn ...n"
  49. _text+="| L BASH_SOURCE{BASH_LINENO called from}.FUNCNAME n"
  50. _text+="| ---------------------------------------------------n"
  51. while (( $i > 0 ))
  52. do
  53. _text+="| $i ${T}$(inspFnStackItem $i)n"
  54. T+=" "
  55. ((--i))
  56. done
  57. #
  58. printf "$_textn"
  59. #
  60. return 0
  61. }
  62.  
  63. function inspFnStackItem () {
  64. local _i=$1
  65. local _fn=${FUNCNAME[$_i]}; [[ $_fn =~ source|main ]] || _fn+="()"
  66. local _at="${BASH_LINENO[$_i-1]}"; [[ $_at == 1 ]] && _at="trap"
  67. local _item="${BASH_SOURCE[$_i]}{${_at}}.$_fn"
  68. #
  69. printf "%s" "$_item"
  70. return 0
  71. }
  72.  
  73. function inspFnStackTop () {
  74. # top stack item is 1 less than length of FUNCNAME array stack
  75. printf "%dn" $(( ${#FUNCNAME[@]} - 1 ))
  76. #
  77. return 0
  78. }
  79.  
  80. $ . sourced.sh
  81. bash
  82. $ source sourced.sh
  83. bash
  84. $ chmod +x sourced.sh
  85. $ ./sourced.sh
  86. ./sourced.sh
  87. $ cat ./sourced.sh
  88. echo $0
Add Comment
Please, Sign In to add comment