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

前端 未结 3 693
一向
一向 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:35

    Personally I usually use

    set +o nounset # same as set -u
    

    on most of my scripts, therefore I always turn it off and back on.

    #!/usr/bin/env bash
    
    set +u
    if [ -n "$PRINTF_SCRIPT_USAGE_SH" ] ; then
        set -u
        return
    else
        set -u
        readonly PRINTF_SCRIPT_USAGE_SH=1
    fi
    

    If you do not prefer nounset, you can do this

    [[ -n "$PRINTF_SCRIPT_USAGE_SH" ]] && return || readonly PRINTF_SCRIPT_USAGE_SH=1
    

提交回复
热议问题