![](/img/trans.png)
[英]How to get the exit code from a bash script invoked with winApi CreateProcess?
[英]How to get the exit code from the source script
我有兩個腳本主腳本和子腳本,我使用源腳本調用了下腳本,如果未安裝指定的軟件包,則應返回退出代碼1。
如果使用bash main.sh
運行主腳本,則無法從主腳本獲取subScriptExitCode
主腳本
source "sub.sh"
subScriptExitCode=$?
log "subScript ExitCode: $subScriptExitCode"
if [ $subScriptExitCode -ne 0 ]; then
exit $subScriptExitCode
fi
子腳本
type -p <package>
subScriptExitCode=$?
if [ $subScriptExitCode -ne 0 ]; then
exit 1
fi
源文件時,請勿使用exit
,因為這將終止整個執行。 而是在sub.sh中使用return
:
返回[n]
使函數以n指定的返回值退出。 如果在函數外部使用,但在腳本執行期間使用。 (源)命令,它將使外殼程序停止執行該腳本,並返回n或腳本中最后執行的命令的退出狀態作為腳本的退出狀態。 如果在函數外部而不是在腳本執行期間使用。,則返回狀態為false。
type -p <package>
subScriptExitCode="$?"
if [ "$subScriptExitCode" -ne 0 ]; then
return 1
fi
而不是采購子腳本,而是按以下方式運行並檢查返回代碼
Main.sh
sh sub.sh
subScriptExitCode=$?
log "subScript ExitCode: $subScriptExitCode"
if [ $subScriptExitCode -ne 0 ]; then
exit $subScriptExitCode
fi
如果您查看Bash的手冊,則請閱讀
source filename [arguments]
:在當前Shell環境中從filename讀取並執行命令,並返回從filename
執行的最后一條命令的退出狀態 。 如果filename
不包含...資料來源:
man bash
這些是與您的問題相關的兩個非常重要的屬性:
如果您的sub_script
遇到的subScriptExitCode
不同於零。 由於exit
語句, main_script
立即終止main_script
。
該main_script
將設置subScriptExitCode
的if語句的退出狀態。 如果subScriuptExitCode
的sub_script
等於0
則為零。
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
: ...退出狀態是最后執行的命令的退出狀態,如果沒有條件測試為真,則為零。資料來源:
man bash
僅使用source
屬性可以解決問題的一種可能方法是:
sub_script
:
type -p <package>
[ $? -eq 0 ]
在這里,如果type p <package>
以零終止,則測試命令將以狀態0
退出,否則, test
命令將以狀態1
退出。 然后在您的main_source
這種狀態main_source
為$?
。 但是,由於type -p
只能返回0
或1
,因此您可以擺脫test
並將sub_script
減少為:
type -p <package>
type [-aftpP] name [name ...]
: ...如果找到所有參數,則type
返回true;如果未找到任何參數,則返回false。[來源:
man bash
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.