2016-01-14 188 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開始。 –

相關問題