[英]How to tell whether current bash script was invoked from call script
我有一個理想情況下將以兩種不同方式使用的腳本。 一,從命令行獨立運行。 兩個從位於 /etc/init.d 中的服務腳本調用。
我希望腳本(稱為 run_app.sh)按如下方式工作:
#/bin/bash
# this is run_app.sh. It should be able to be run stand-alone or called from another script
if [ invoked by a calling script ] then
java -cp . -jar blah.jar
else
nohup java -cp . -jar blah.jar 2>&1 &
,所以它是我需要幫助的“由調用腳本調用”。 謝謝你。
如果您計划通過發出./run_app.sh
或服務來啟動您的腳本。 你可以只使用$0
:
#!/bin/bash
# this is run_app.sh. It should be able to be run stand-alone or called from another script
this_script_name="run_app.sh"
if [ "$0" == "./${this_script_name}" ] then
java -cp . -jar blah.jar
else
nohup java -cp . -jar blah.jar 2>&1 &
我建議使用命令行參數,而不是試圖找出腳本的調用方式。
腳本app.sh
#/bin/bash
# this is run_app.sh. It should be able to be run stand-alone or called from another script
if [ "$1" = "--service" ] then
java -cp . -jar blah.jar
else
nohup java -cp . -jar blah.jar 2>&1 &
fi
從調用腳本 run app.sh --service
手動將腳本作為app.sh
運行。
如果您需要向腳本傳遞額外的命令行參數,您可能需要實現一些更好的選項解析。
注意:檢查$0
在某些情況下可能有效,但在其他一些情況下可能無效。 試圖找出有關父進程的詳細信息更加困難和脆弱。
另一個注意事項:您的java
命令行參數-cp . -jar blah.jar
-cp . -jar blah.jar
依賴於當前目錄。 為了確保這在所有情況下都有效,腳本應該在調用java
之前cd
到正確的目錄中。 例如cd $(dirname "$0")
如果腳本與blah.jar
位於同一目錄中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.