如何在shell脚本的函数中返回传递的参数?

时间:2018-10-04 13:29:38

标签: shell

下面是我开发的代码。我在函数中传递了四个参数,并且想要返回变量输出,我将其作为第四参数传递给该函数。我收到以下提到的错误。

test.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行:output = FAILED:找不到命令

     

./ test.sh:第18行:返回:输出:需要数字参数

     

result =

1 个答案:

答案 0 :(得分:0)

这里有很多问题:

  • 尝试将值分配给变量 value (这是您看到的“ output = FAIL”错误的原因)
  • 将数组作为一等值传递
  • 收集函数的输出

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