如何读取shell脚本中函数返回的值



我编写了一个shell脚本,将数组作为参数传递给函数,然后选择该数组中的一个元素并将其返回给调用者。除非将函数调用的返回分配给变量,否则脚本运行良好。

#!/bin/bash
operations=(Sleep Eat Play Study)
services=(Cook Clean Draw)
readOption(){
_arr=("$@")
#echo "${_arr[@]}"
#echo "Value of #1 is $@"
MAX_TRIES="5";
COUNT="0";
while [[ -z "$opt" && "$COUNT" -lt "$MAX_TRIES" ]]
do
if [ "$COUNT" != "0" ]
then
echo "WARN: Retries left [$((MAX_TRIES-COUNT))]. Choose the correct option."
fi
for i in "${!_arr[@]}";
do
echo $((i+1)). "${_arr[$i]}"
done
read -rp "Choose an option>" index;
COUNT="$((COUNT+1))"
opt="${_arr[$((index-1))]}"
done

if [ "$COUNT" -eq "$MAX_TRIES" ]
then
echo "ERROR: Exceeded maximum number of retries: $MAX_TRIES";
echo "Exiting......";
exit 1;
fi
value="${opt,,}"   # Lower casing the chosen option
unset opt
echo "${value}"
}
opr=$( readOption "${operations[@]}" )  # It works fine if I remove the assignment
svc=$( readOption "${services[@]}" )    # It works fine if I remove the assignment
echo "Operation is: $opr"
echo "Service is: $svc"

脚本不能按预期工作的作业出了什么问题?感谢

更新日期-1:

预期输出:

我想显示所有数组元素。允许用户从数组中选择一个选项。将函数中选择的选项返回到主脚本中的变量。

更新-2:

按照已接受的答案中的建议更新了脚本。

$(...)从里面获取stdout。因此:

readOption() {
read -p "This is printed on stdout!" ...
echo "this is also printed on stdout"
echo "${value}"      # and this is too!
}
opt=$(readOption)  # takes **ALL** stdout messages and assigns them to opt

我相信对你来说,目前的方法最好是纠正所有引用错误,并与http://shellcheck.net并按名称传递变量名并使用namereference,以模拟read:

readOption() {
local opt value _arr COUNT MAX_TRIES  # do not pollute global space
declare -n _readoption_var=$1 # namereference - use unique name to avoid nameclashes
shift
_arr=("$@") # properly quote varibale expansions
... etc. etc. your code ...
_readoption_var="$value"
}
readOption opr "${operations[@]}"

或者,您可以手工选择消息,并将输出与写入stdout:分开写入控制台

readOption() {
read -p "Print to console" var >&3 
echo "print this to console too" >&3
echo "$value" # but print this to stdout
} 
exec 3>&1 # duplicate/"clone" stdout on 3rd file descirptor
opt=$(readOption)  # stdout will go to opt
# but fd3 will go to terminal
# or:
opt=$(readOption) 3>&1

最新更新