如何从函数中的读取命令 return 数组?
How to return an array from read command in a function?
bash
这里有个小问题
我在一个简单的 function
中写了一个 array
,我需要 return
它作为 array
和 read
命令,还需要 call
它不知何故。
function myData {
echo 'Enter the serial number of your items : '
read -a sn
return ${sn[@]}
}
比如像这样???
$ ./myapp.sh
Enter the serial number of your items : 92467 90218 94320 94382
myData
echo ${?[@]}
为什么我们这里没有像其他语言那样的 return 值?
感谢您的帮助...
正如其他人提到的,内置命令 return
旨在将 exit status
发送给调用者。
如果想将函数中处理的结果传递给
来电者,会有以下几种方式:
使用标准输出
如果你在一个函数中向标准输出写入一些东西,输出
被重定向到调用者。标准输出只是一个非结构化的
字节流。如果你想让它有一个特殊的意义,比如
array
,你需要通过为一些分配分隔符来定义结构
人物)。如果您确定每个元素不包含 space、制表符或
换行符,你可以依赖默认值 IFS
:
myfunc() {
echo "92467 90218 94320 94382"
}
ary=( $(myfunc) )
for i in "${ary[@]}"; do
echo "$i"
done
如果数组的元素可能包含白色space或其他特殊
字符,您需要保留它们(例如您正在处理的情况
文件名),您可以使用空字符作为分隔符:
myfunc() {
local -a a=("some" "elements" "contain whitespace" $'or \nnewline')
printf "%s[=11=]" "${a[@]}"
}
mapfile -d "" -t ary < <(myfunc)
for i in "${ary[@]}"; do
echo ">$i" # The leading ">" just indicates the start of each element
done
按引用传递
与其他语言一样,bash
>=4.3 有一种机制来传递变量
参考或按名称:
myfunc() {
local -n p="" # now p refers to the variable with the name of value of
for (( i=0; i<${#p[@]}; i++ )); do
((p[i]++)) # increment each value
done
}
ary=(0 1 2)
myfunc "ary"
echo "${ary[@]}" # array elements are modified
使用数组作为全局变量
用法就不用多说了pros/cons.
希望对您有所帮助。
bash
这里有个小问题
我在一个简单的 function
中写了一个 array
,我需要 return
它作为 array
和 read
命令,还需要 call
它不知何故。
function myData {
echo 'Enter the serial number of your items : '
read -a sn
return ${sn[@]}
}
比如像这样???
$ ./myapp.sh
Enter the serial number of your items : 92467 90218 94320 94382
myData
echo ${?[@]}
为什么我们这里没有像其他语言那样的 return 值? 感谢您的帮助...
正如其他人提到的,内置命令 return
旨在将 exit status
发送给调用者。
如果想将函数中处理的结果传递给
来电者,会有以下几种方式:
使用标准输出
如果你在一个函数中向标准输出写入一些东西,输出 被重定向到调用者。标准输出只是一个非结构化的 字节流。如果你想让它有一个特殊的意义,比如
array
,你需要通过为一些分配分隔符来定义结构 人物)。如果您确定每个元素不包含 space、制表符或 换行符,你可以依赖默认值IFS
:myfunc() { echo "92467 90218 94320 94382" } ary=( $(myfunc) ) for i in "${ary[@]}"; do echo "$i" done
如果数组的元素可能包含白色space或其他特殊 字符,您需要保留它们(例如您正在处理的情况 文件名),您可以使用空字符作为分隔符:
myfunc() { local -a a=("some" "elements" "contain whitespace" $'or \nnewline') printf "%s[=11=]" "${a[@]}" } mapfile -d "" -t ary < <(myfunc) for i in "${ary[@]}"; do echo ">$i" # The leading ">" just indicates the start of each element done
按引用传递
与其他语言一样,
bash
>=4.3 有一种机制来传递变量 参考或按名称:myfunc() { local -n p="" # now p refers to the variable with the name of value of for (( i=0; i<${#p[@]}; i++ )); do ((p[i]++)) # increment each value done } ary=(0 1 2) myfunc "ary" echo "${ary[@]}" # array elements are modified
使用数组作为全局变量
用法就不用多说了pros/cons.
希望对您有所帮助。