2016-01-14 164 views
3

有没有办法检测shell脚本是直接调用还是从另一个脚本调用。如何检测是否从另一个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 
+0

你为什么想这样做?聪明的系统管理员可以轻松地编写一些小型C程序来封装内部shell脚本。 –

+0

'./ child.sh'使用自己的解释器将子脚本作为外部可执行文件运行,就像其他任何程序调用外部可执行文件一样。你当然可以做一些丑陋而脆弱的事情,比如在流程树中查找你的父PID,但是再次看到:丑陋而脆弱。 –

+1

...如果你真正的目标是不同的,即。为了检测交互式和脚本式调用,有更好的方法来做到这一点(例如,脚本化调用通常不会有TTY,除非父脚本本身是由用户调用的)。同样,如果你想支持类似非交互式批处理模式的东西,那么最好的形式是使该切换成为显式的,如果不是通过参数,那么通过环境变量,可选地自动启用而不存在TTY。 –

回答

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 

$SHLVL在父shell设置为1,将被设置为大于2(取决于嵌套)当你的脚本是从其他脚本调用。

+1

如果父shell是'zsh'外壳将不起作用 –

+2

嗯,这是基于'bash'标记 – anubhava

+0

不保证交互shell将SHLVL为1;它可能已经更高了。例如:我在外壳中的SHLVL为1,但是从tmux开始实际工作,并且在那里它从2开始。 –

相关问题