首页 > 解决方案 > 如何在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 行:返回:输出:需要数字参数

结果=

标签: shell

解决方案


这里有很多问题:

  • 尝试为变量值赋值(这是您看到的“输出=失败”错误的原因)
  • 将数组作为一等值传递
  • 收集函数的输出

目前尚不清楚 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"    

推荐阅读