有没有办法检测一个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
./child.sh
会将子脚本作为外部可执行文件运行,拥有自己的解释器,就像任何其他程序调用外部可执行文件一样。当然,你可以做一些丑陋而脆弱的事情,比如在进程树中查找父进程ID,但请再次参考丑陋和脆弱。 - Charles Duffy