有沒有辦法檢測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
你爲什麼想這樣做?聰明的系統管理員可以輕鬆地編寫一些小型C程序來封裝內部shell腳本。 –
'./ child.sh'使用自己的解釋器將子腳本作爲外部可執行文件運行,就像其他任何程序調用外部可執行文件一樣。你當然可以做一些醜陋而脆弱的事情,比如在流程樹中查找你的父PID,但是再次看到:醜陋而脆弱。 –
...如果你真正的目標是不同的,即。爲了檢測交互式和腳本式調用,有更好的方法來做到這一點(例如,腳本化調用通常不會有TTY,除非父腳本本身是由用戶調用的)。同樣,如果你想支持類似非交互式批處理模式的東西,那麼最好的形式是使該切換成爲顯式的,如果不是通過參數,那麼通過環境變量,可選地自動啓用而不存在TTY。 –