shell - 如何在shell脚本中返回函数中传递的参数?
问题描述
下面是我开发的代码。我在函数中传递了四个参数,并希望返回变量输出,我将其作为参数号 4 传递给该函数。我收到下面提到的错误。
测试.sh
output='PASS'
A=(1.0,1.0,1.0,1.0,0.0,1.0)
T=(1,2,3,4,5,6)
function compare(){
j=0
for i in "$2"
do
if [[ "$3" = '1.0' ]]
then
"$4"="PASS"
echo -e "\nA:$3 and T:$i sec" >> "$1"
else
"$4"="FAIL"
echo -e "\nA:$3 and T:$i sec" >> "$1"
fi
j=$(( $j + 1 ))
done
return "$4"
}
result=compare $1 ${A[@]} ${T[@]} output
echo "result:$result"
当我打电话时./test.sh file.txt
,我收到以下错误:
./test.sh:第 13 行:输出=失败:找不到命令
./test.sh:第 18 行:返回:输出:需要数字参数
结果=
解决方案
这里有很多问题:
- 尝试为变量值赋值(这是您看到的“输出=失败”错误的原因)
- 将数组作为一等值传递
- 收集函数的输出
目前尚不清楚 A 和 T 是如何相关的(安定下来,techbros),但看起来 T 包含您要在 A 中查找的索引。
#!/bin/bash
# validate the bash version at least 4.4 here.
function compare(){
local file=$1
local -n arrayA=$2
local -n arrayT=$3
local -n resultVar=$4
resultVar=PASS
for i in "${arrayT[@]}"; do
if [[ "${arrayA[i]}" != '1.0' ]]; then
resultVar=FAIL
# normally I would return here, but you want to log the whole array
fi
printf "A:%f and T:%d sec\n" "${arrayA[i]}" "$i" >> "$file"
done
}
output='PASS'
T=(1 2 3 4 5 6)
A=([1]=1.0 1.0 1.0 1.0 0.0 1.0) # force A to start with index 1, corresponding to the first element of T
compare "$1" A T output
echo "result:$output"
推荐阅读
- nginx - Meteor 默认代理
- gulp - 由 gulp-sourcemaps 生成的内联源映射在 VS 代码调试器中不起作用
- excel - 如何 - 如果单元格的值等于工作簿任何选项卡中另一个单元格的值,则对其进行条件格式设置
- monitoring - Icinga2:每个服务基础的重新通知间隔
- visual-studio - 出现无法启动调试...启动项目无法启动。为什么?
- java - 我的 do 语句中的缩进出错
- node.js - Nodejs 无法识别我的 server.js 路径
- javascript - iOS 项目中缺少的 .a 文件
- cloud - 我可以在云环境中使用 AgensGraph 吗?
- git - Git 用户名不会改变