0

I would like to write a function in bash that takes two array parameters like this:

#!/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)

Is this possible and if yes, what is the correct syntax? Both when calling the function, as well as inside the function to process the arrays?

RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • You have multiple options. You can use a delimeter to separate arguments from one array and another. You can pass array sizes and arrays themselves. You can pass arrays by name and reference them from the function. You can double escape arrays (ex. by `declare -p` and `printf "%q"`) and pass one array in one argument. You can pass one array using stdin and the other using arguments. – KamilCuk Feb 09 '19 at 23:35
  • Functions can't take array parameters, because there are no array *values* in `bash`. All you can do is pass each element of an array as a separate argument, or pass the *name* of an array as a value (which then requires some hoops to access the global variable by that name). – chepner Feb 10 '19 at 20:05

1 Answers1

-2

Source code of 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[@]}"

After execution:

# ./RemoveElements.sh
1 5 8

As you see the desired output.

Learner
  • 1
  • 2
  • 1
    If `RemoveElements` is going to refer to `a` and `b` by name, there's no reason to pass any arguments. In fact, `RemoveElements` as shown here *ignores* its arguments. – chepner Feb 10 '19 at 20:06