【问题标题】:How to detect being source'd as opposed to being run in a shell script? [duplicate]如何检测源代码而不是在 shell 脚本中运行? [复制]
【发布时间】:2017-11-11 14:06:39
【问题描述】:

在 python 中,您可以检测一个脚本是否被另一个脚本执行 imported 这个

if __name__ == '__main__':
    # We are run directly.

有没有办法在 shell 脚本中做同样的事情? 我在脚本中有几个函数,我希望能够在不执行它们的情况下获取它们。

【问题讨论】:

  • 为什么不将函数声明和环境变量等安全内容保留在源文件中,并将任何正在执行的代码移至不同的脚本文件?
  • 您的问题似乎与标签 python 没有任何实际关系,请删除该标签?
  • @HåkenLid 当一个任务需要在多个文件中分离时,我倾向于开始认为它对于 shell 脚本来说可能太大了。当然,除非是为了弄乱我的 .profile。 ;-)
  • 您是否尝试过寻找解决方案? stackoverflow.com/questions/2683279/…
  • @barny 我正在寻找与 Python 中的某些东西等效的 shell。 stackoverflow.com/q/573585/383793 也被标记为 [git] 和 [svn]

标签: python bash shell


【解决方案1】:

到目前为止,我想出了这些:

if [ "$0" != "bash" ]
then
    # We are run directly because
    # $0 == our filename
    # Or is it? It could be a different shell!
fi

if [ "$(basename $0)" = "foo.sh" ]
then
    # We are run directly, because $0 == our filename.
    # But what if we get mv'ed to some other filename???
fi

有没有更脆弱的解决方案?

【讨论】:

  • 您的第一个解决方案似乎很好。如果你想支持其他shell,只需将它们添加到条件中即可。
猜你喜欢
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2012-11-14
  • 2013-03-06
相关资源
最近更新 更多