簡體   English   中英

如何從源腳本獲取退出代碼

[英]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。

sub.sh

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

這些是與您的問題相關的兩個非常重要的屬性:

  1. 如果您的sub_script遇到的subScriptExitCode不同於零。 由於exit語句, main_script立即終止main_script

  2. main_script將設置subScriptExitCode的if語句的退出狀態。 如果subScriuptExitCodesub_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只能返回01 ,因此您可以擺脫test並將sub_script減少為:

type -p <package>

type [-aftpP] name [name ...] ...如果找到所有參數,則type返回true;如果未找到任何參數,則返回false。

[來源: man bash ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM