Is there any mechanism in Shell script alike “include guard” in C++?

前端 未结 3 692
一向
一向 2021-02-06 04:55

let\'s see an example: in my main.sh, I\'d like to source a.sh and b.sh. a.sh, however, might have already sourced b.sh. Thus it will cause the codes in b.sh executed twice. Is

3条回答
  •  面向向阳花
    2021-02-06 05:21

    If you're sourcing scripts, you are usually using them to define functions and/or variables.

    That means you can test whether the script has been sourced before by testing for (one of) the functions or variables it defines.

    For example (in b.sh):

    if [ -z "$B_SH_INCLUDED" ]
    then
        B_SH_INCLUDED=yes
        ...rest of original contents of b.sh
    fi
    

    There is no other way to do it that I know of. In particular, you can't do early exits or returns because that will affect the shell sourcing the file. You don't have to use a name that is solely for the file; you could use a name that the file always has defined.

提交回复
热议问题