0

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?

4
  • You are passing the array as individual args to execute and then only passing the first one the makeNecessaryDirectory, so $@ is just 1. Commented Sep 21, 2015 at 8:10
  • Wouldn't your expected output be 1, 1, 2, 3, 4, 5 (all on separate lines)? Commented Sep 21, 2015 at 8:45
  • @gniourf_gniourf, the code portion is edited on makenecessaryDirectory. Commented Sep 21, 2015 at 8:49
  • Ok. Then why don't you just use execute() { "$@"; }? it seems that's what you're after… Commented Sep 21, 2015 at 8:50

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution, i will use it. But how can I achieve the expected output with passing the array elements?
@AhsanulHaque You can't really, you can't pass array elements, whilst still maintaining the array. Any embedded spaces would be lost. This is the only way i know of to preserve the array as it is between functions. You could use shift in execute, and then set servername to $@, but that is not a very good way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.