Shell脚本中是否有任何类似于"include guard"的机制?在C ++中? [英] Is there any mechanism in Shell script alike "include guard" in C++?

查看:135
本文介绍了Shell脚本中是否有任何类似于"include guard"的机制?在C ++中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看一个例子:在我的main.sh中,我想获取a.sh和b.sh的源代码.但是,a.sh可能已经来源b.sh.因此,这将导致b.sh中的代码执行两次. C ++中是否有任何类似包含防护"的机制?

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++?

推荐答案

如果要采购脚本,通常会使用它们来定义函数和/或变量.

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.

例如(在b.sh中):

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

我知道没有其他方法可以做到这一点.特别是,您不能提早退出或返回,因为这会影响Shell采购文件.您不必使用仅用于文件的名称.您可以使用文件始终定义的名称.

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.

这篇关于Shell脚本中是否有任何类似于"include guard"的机制?在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆