我有一個 bash 腳本,它呼叫一個回傳值的函式。我已包含以下腳本:
腳本
source ./utilities/function1.sh
result=$(Function1)
echo "Result: $result"
功能1
function Function1 {
echo "Inside Function: Function1"
cat <<EOF
this is the result
EOF
}
我希望能夠在函式內回顯到控制臺并僅回傳我想要的值,不包括回顯到控制臺的訊息,但是當我運行腳本時,將回傳以下內容:
Result: Inside Function: Func1
this is the result
這是從 bash 函式回傳值的最佳方法,還是有一種方法可以回顯到控制臺并回傳一個值,而無需從函式中回傳回顯命令的內容?
提前致謝
uj5u.com熱心網友回復:
有幾種方法可以做你想做的事。兩個簡單的是:
使用 STDERR 回顯到控制臺并在腳本中捕獲 STDOUT。默認情況下,STDOUT 位于檔案描述符 1 上,STDERR 位于檔案描述符 2 上:
function myFunction() {
echo "This goes to STDOUT" >&1 # '>&1' is the default, so can be left out.
echo "This goes to STDERR" >&2
}
result=$(myFunction)
echo ${result}
使用變數將字串回傳給呼叫者:
function myFunction() {
echo "This goes to STDOUT"
result="This goes into the variable"
}
declare result="" # Has global scope. Can be modified from anywhere.
myFunction
echo ${result}
全域范圍變數不是好的編程習慣,但在 bash 腳本中卻是必不可少的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464581.html
上一篇:PowerQuery:如何從文本中洗掉變音符號/重音符號
下一篇:將數學運算從 反轉為-
