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

余生颓废 提交于 2019-12-14 00:16:25

问题


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 there any mechanism alike "include guard" in C++?


回答1:


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.




回答2:


In bash, an early return does not affect the sourcing file, it returns to it as if the current file were a function. I prefer this method because it avoids wrapping the entire content in if...fi.

if [ -n "$_for_example" ]; then return; fi
_for_example=`date`



回答3:


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


来源:https://stackoverflow.com/questions/7518584/is-there-any-mechanism-in-shell-script-alike-include-guard-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!