這個問題在這里已經有了答案: Bash 函式中的回傳值 11 個答案 2天前關閉。
我制作了以下函式來計算陣列的最大值:
MaxArray(){
aux ="$1"
for n in "$@"
do
[ "$n" -gt "$aux" ] && aux="$n"
done
return $aux
}
我嘗試將 return 更改為 echo "$aux" 以查看它是否正確計算了該值并且是否有效。使用具有以下值的陣列:(1, 10, 152, 0, 3),我嘗試回傳并像這樣呼叫函式:
value=$( MaxArray ${array[@]} )
echo "value is $value"
但是呼叫函式后 $value 為空。如何正確地將函式的回傳分配給 $value?
uj5u.com熱心網友回復:
您不會回傳return用于回傳退出狀態的值。您可以通過將值發送到標準輸出 ( echo, printf...) 來回傳一個值 如果您的 bash 足夠新,那么避免子 shell 的更好解決方案是將變數名稱作為函式引數傳遞并使用命名參考 ( local -n var=name):
MaxArray(){
local -n tmp="$1"
local -i n
tmp="$2"
shift 2
for n in "$@"; do
[ "$n" -gt "$tmp" ] && tmp="$n"
done
}
然后:
$ unset value
$ MaxArray value 1 2 3 4 5 4 3 2 1
$ echo $value
5
請注意,如果您的值存盤在索引陣列中,您可以使用相同的原則來傳遞其名稱而不是其內容:
$ MaxArray(){
local -n tmp="$1"
local -n arr="$2"
local -i n
tmp="${arr[0]}"
for n in "${arr[@]}"; do
[ "$n" -gt "$tmp" ] && tmp="$n"
done
}
$ declare -a values=( 1 2 3 4 5 4 3 2 1 )
$ unset value
$ MaxArray value values
$ echo $value
5
uj5u.com熱心網友回復:
在 shell 中,傳遞值是通過輸出完成的,而不是回傳碼:
#!/bin/bash
MaxArray() {
local n aux="$1"
for n in "$@"
do
(( n > aux )) && aux=$n
done
echo "$aux"
}
value=$( MaxArray "${array[@]}" )
uj5u.com熱心網友回復:
代替
return $aux
和
echo "$aux"
命令替換捕獲標準輸出,而不是退出狀態。
順便說一句,變數賦值不應該在等號之前或之后有空格,賦值應該是
aux="$1"
uj5u.com熱心網友回復:
函式有多種回傳值的方法:
第一種方法是在全域變數中提供結果。此方法也適用于所有 POSIX-shell 變體:
#!/bin/sh
# Here we use the global ret variable to get the result of the function
ret=
max() {
ret=$1
shift
for n
do
[ "$n" -gt "$ret" ] && ret=$n
done
}
max 1 8 2 7 42 23 17
printf 'The maximum of %s is %s\n' '1 8 2 7 42 23 17' "$ret"
另一種常用方法也是 POSIX-shell 友好的。它涉及將結果流式傳輸到stdout(列印),并在呼叫函式時將其捕獲到變數中。這涉及一個子外殼,因此應避免在回圈中使用:
#!/bin/sh
max() {
gtst=$1
shift
for n
do
[ "$n" -gt "$gtst" ] && gtst=$n
done
# Print the result
printf %s "$gtst"
}
# Capture the printout of max into the ret variable
ret=$(max 1 8 2 7 42 23 17)
printf 'The maximum of %s is %s\n' '1 8 2 7 42 23 17' "$ret"
第三種方法涉及通過名稱間接尋址變數,使用eval:
#!/bin/sh
max() {
# Get the name of the return variable
ret_name=$1
shift
gtst=$1
shift
for n
do
[ "$n" -gt "$gtst" ] && gtst=$n
done
# Evaluate expression to assign returned value to provided variable name
eval "$ret_name=$gtst"
}
# will get the result into the variable ret
max ret 1 8 2 7 42 23 17
# shellcheck disable=SC2154 # dynamically referrenced ret
printf 'The maximum of %s is %s\n' '1 8 2 7 42 23 17' "$ret"
最后,此方法使用 nameref 變數,這些變數僅適用于從 4.2 版開始的 Bash:
#!/bin/bash
max() {
# Get the name of the return variable into a nameref variable
local -n gtst=$1
local -i n
shift
gtst=$1
shift
for n
do
declare -p gtst
[ "$n" -gt "$gtst" ] && gtst=$n
done
}
# will get the result into the variable ret
declare -i ret
max ret 1 8 2 7 42 23 17
# shellcheck disable=SC2154 # dynamically referrenced ret
printf 'The maximum of %s is %s\n' '1 8 2 7 42 23 17' "$ret"
所有版本的相同輸出:
The maximum of 1 8 2 7 42 23 17 is 42
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487313.html
上一篇:在特定點bash中插入新行
