多个返回值

函数

#函数把各个值打印在一行里,
#read 再把这一行拆分到各变量中
getFirstLast() {
    local first=-1
    local last=-1
    if (($# > 0)); then
        first=$1
        #${@: -1} 是最后一个参数
        last=${@: -1}
    fi
    echo "$first $last"
}

lst=(2 3 5)
read -r first last <<< "$(getFirstLast "${lst[@]}")"
#first is 2
#last is 5

#陷阱:管道末端的 read 在子 shell 中运行,
#它的变量会随子 shell 一起消失
fromPipe=0
getFirstLast "${lst[@]}" | read -r fromPipe rest
#fromPipe is 0

echo "first is $first"
echo "last is $last"
echo "fromPipe is $fromPipe"