如何检测是否从另一个shell脚本调用shell脚本

时间:2016-01-14 21:21:15

标签: linux bash shell

有没有办法检测shell脚本是直接调用还是从另一个脚本调用。

parent.sh

#/bin/bash
echo "parent script"
./child.sh

child.sh

#/bin/bash
echo -n "child script"
[ # if child script called from parent ] && \
    echo "called from parent" || \
    echo "called directly" 

结果

./parent.sh
# parent script
# child script called from parent

./child.sh
# child script called directly

1 个答案:

答案 0 :(得分:2)

您可以像这样使用child.sh

#/bin/bash
echo "child script"

[[ $SHLVL -gt 2 ]] &&
  echo "called from parent" ||
  echo "called directly"

现在运行它:

# invoke it directly
./child.sh
child script 2
called directly

# call via parent.sh
./parent.sh
parent script
child script 3
called from parent
在父shell中将

$SHLVL设置为1,并在从其他脚本调用脚本时将其设置为大于2(取决于嵌套)。