Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Error while passing array as function parameter in bash

This is the code I am dealing with:

function execute {
    task="$1"
    servername="$2"
    "$task" "${servername[@]}" 

}


function someOtherThing {

    val=$1
    echo "$val"

}


function makeNecessaryDirectory {

    arr=("$@")
    echo "${arr[@]}"

}


dem=(1 2 3 4 5)


execute someOtherThing 1
execute makeNecessaryDirectory "${dem[@]}"

Output:

1
1

Expected output:

1
1 2 3 4 5

How to achieve this? I found no error logically.

Side question:

Is it safe to always receive 2nd parameter as an array inside execute so that it can deal with both of the dependent functions, or i should have an explicit check inside execute?

Upvotes: 0

Views: 46

Answers (1)

123
123

Reputation: 11216

As explained in my comment

You are passing the array as individual args to execute and then only passing the first one the makeNecessaryDirectory, so $@ is just the single argument passed which is 1.

I would do it this way, I have added comments to the parts i have changed. It is only minor changes but should hopefully work for you.

#!/bin/bash

function execute {
    task="$1"
    servername="$2"
    "$task" "$servername"
    #No longer pass array here just pass servername as the name of array

}


function someOtherThing {

    val=$1
    echo "$val"

}


function makeNecessaryDirectory {

    local arr=("${!1}") 
    #Indirect reference to the first arg passed to function which is now the
    #name of the array

    for i in "${arr[@]}";
       do
           echo "$i"
       done

}


dem=(1 2 3 4 5)


execute someOtherThing 1
execute makeNecessaryDirectory 'dem[@]' #Pass the array name instead of it's contents

Upvotes: 1

Related Questions