如何检测源代码而不是在shell脚本中运行?

2024-05-16 11:58:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

有没有一种方法可以在shell脚本中执行相同的操作? 我在脚本中有几个函数,我希望能够在不执行它们的情况下进行源代码编写


Tags: 方法函数runname脚本if源代码main
1条回答
网友
1楼 · 发布于 2024-05-16 11:58:48

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

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

有没有不那么脆弱的解决方案

相关问题 更多 >