首页 > 解决方案 > bash:具有两个数组参数的函数?如何调用以及如何解析?

问题描述

我想在 bash 中编写一个函数,它接受两个数组参数,如下所示:

#!/bin/bash 

function RemoveElements
{
  # $1 and $2 are supposed to be arrays
  # This function should generate a new array, containing
  # all elements from $1 that did not occur in $2
}

a=(1 3 5 7 8)
b=(2 3 6 7)

c=RemoveElements $a $b 
# or perhaps: (if directly returning non-integer
# values from function is not possible)
c=$(RemoveElements $a $b)

# c should now be (1 5 8)

这可能吗?如果可以,正确的语法是什么?无论是在调用函数时,还是在函数内部处理数组?

标签: arraysbashfunctionargumentsparameter-passing

解决方案


RemoveElements.sh 源代码:

#!/bin/bash
function RemoveElements {
        for i in ${a[@]};do
                MATCH=0
                for j in ${b[@]};do
                        if [ $i -ne $j ];then
                                continue
                        else
                                MATCH=`expr $MATCH + 1`
                        fi
                done
                if [ $MATCH -eq 0 ];then
                        c=(${c[@]} $i)
                fi
        done
}

a=(1 3 5 7 8)
b=(2 3 6 7)

RemoveElements

echo "${c[@]}"

执行后:

# ./RemoveElements.sh
1 5 8

如您所见,所需的输出。


推荐阅读