簡體   English   中英

Bash:調用 function 並檢查返回值

[英]Bash : call a function and check return value

我有一個簡單的腳本可以執行以下操作:

#!/bin/bash

main(){
        test
}

test(){
        local value=$(test2 "hi")
        if [ "$value" == "test hi" ];
        then
                echo "function executed"
        fi
}

test2(){
        echo "test2 executed"
        echo "test $1"
}

main

基本上,我正在嘗試檢查function返回的值並相應地控制執行。 現在,當我執行此操作時,什么都不會打印(甚至test2函數中的echo語句也不打印)。 但是,當我在test function (聲明后)中添加echo $value時,所有內容都會打印出來。

有什么方法可以處理test2返回的值而不顯式回顯返回值。

錯誤消息、調試 output、診斷、狀態更新和進度信息應寫入stderr

test2(){
        echo "test2 executed" >&2
        echo "test $1"
}

stdout應專門用於 function 的基本業務邏輯 output。 這樣,您可以捕獲 pipe 值,而無需將其與調試消息混合:

$ var=$(test2 "hi")
test2 executed
$ echo "The output from the function was <$var>"
The output from the function was <test hi>

在 function 中設置退出代碼,並像任何其他條件一樣檢查它。

$: tst() { [[ foo == "$1" ]]; }
$: someVar=foo
$: if tst "$someVar"; then echo "arg was foo"; else echo "arg was NOT foo"; fi
arg was foo
$: someVar=bar
$: if tst "$someVar"; then echo "arg was foo"; else echo "arg was NOT foo"; fi
arg was NOT foo

默認情況下,任何 function 的退出代碼都是最后執行命令的返回代碼,除非您明確使用exitreturn (在 function 中,它們是同義詞。)

如果需要,您可以創建更復雜的測試 -

tst() {
  case "$1" in
  foo) return 0  ;;
  bar) return 1  ;;
    *) return -1 ;;
  esac
}

tst "$someVar"
case "$?" in
0) echo "was foo" ;;
1) echo "was bar" ;;
*) echo "was unrecognized" ;;
esac

試試看。

暫無
暫無

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

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