Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 1
    Why MY_BASE=$(echo $0)?  MY_BASE=$0 is better. Commented Dec 24, 2022 at 23:30
  • What if mylib.sh is sourced inside other scripts that are supposed to be sourced, and which source other scripts? IINM, when you source a script from your shell, $0 remains the name of the shell (-bash), so inside mylib.sh might be sourced multiple times. Commented Dec 25, 2022 at 9:18
  • @aviro Let me see, what you were saying is similar to source test.sh;sysLOG Hi!, right? As long as the rest part of mylib.sh contains functions only, I think, being sourced multiple times will not cause troubles. Since the goal of $MY_BASE is making debug easier for mylib.sh. Commented Dec 25, 2022 at 12:45
  • 1
    Right, but the question was how to avoid sourcing multiple times. :) You could use ${#BASH_SOURCE[@]} to check if the command is being sourced. For instance: [[ "${MY_BASE:0:1}" != "-" || ${#BASH_SOURCE[@]} -gt 1 ]] (this means that its source level is greater than 1, which means it's been sourced by another file being source). Commented Dec 25, 2022 at 13:48
  • @aviro Thank you for the tips, I didn't know I could do that. Unfortunately sh doesn't have $BASH_SOURCE, it gives out errors. I will dig more about it. If I can come out more suitable solutions I will edit my answer. Commented Dec 26, 2022 at 14:53