【问题标题】:How to determine if a shell script file is sourced in Bash [duplicate]如何确定 shell 脚本文件是否来自 Bash [重复]
【发布时间】:2012-04-08 15:50:54
【问题描述】:

我想知道如何确定一个脚本文件是否被执行或获取。

例如,

# Shell script filename build.sh
if [ "x$0" = "xbash" ]; then
    echo "I am sourced by Bash"
else
    echo "I am executed by Bash"
fi

如果我输入了

source build.sh

它会输出I am sourced by Bash。

如果我输入了

./build.sh

它会输出我被 Bash 执行。

目前,我使用 $0 来执行此操作。有更好的主意吗?

受到Tripeee的启发,我找到了更好的方法:

#!/bin/bash

if [ "x$(awk -F/ '{print $NF}' <<< $0)" = 'xcdruntime' ]; then
    echo Try to source me, not execute me.
else
    cd /opt/www/app/pepsi/protected/runtime
fi

【问题讨论】:

  • 您的解决方案不起作用,因为您可以通过bash build.sh 运行脚本。另请注意,脚本可能会自行获取 - 这有点愚蠢,但可能。
  • @Pumbaa80 嗯...我已经尝试过bash build.sh 我的解决方案仍然有效
  • 有趣:永远不要调用你的源脚本bash,否则你会感到困惑!
  • 您不需要x 标记来防范空字符串。

标签: bash shell


【解决方案1】:

如果来自另一个脚本,它就不起作用。我会反其道而行之;

test "X$(basename -- "$0")" = "Xbuild.sh" || echo Being sourced

更新:为两个字符串添加了 X 前缀。

也更新:在basename 调用中添加了双破折号。

【讨论】:

  • 是的,你的解决方案比我的好。如果脚本来源于另一个脚本,$0 将不是bash
  • 哎呀,你是对的。更新了我的答案。感谢您的反馈。
  • 实际上你可以使用$(basename -- "$0") 来解决这个问题。双破折号在我的 basename 版本中没有记录,但得到了广泛支持。
  • 您不需要在字符串前面加上“X”。只要你同时引用它们,test 就会正确处理你扔给它的任何字符串,无论它是空的还是以破折号开头。
  • test 的现代版本可以处理以破折号开头的值,但这并不总是正确的。
猜你喜欢
  • 2012-07-05
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
相关资源
最近更新 更多