Pass array to function parameter in terminal inside for loop

I have the following code:

myfunc(){ group=("$1") for i in "${group[@]}" do printf "%s\n" "$i" done
}

I am using it to print every item in the group array. This array should be a parameter in the terminal. But when I try to use it in the terminal inside the .bash_profile file it doesnt work. I am trying this by running the following command:

myfunc ("one" "two" "three")
0

1 Answer

You seem to be expecting the shell to generate some kind of anonymous array variable - AFAIK that's not possible in bash.

The simple approach is to pass individual arguments (which may contain whitespace, if properly quoted) and then refer to them with "$@"

myfunc ()
{ group=("$@"); for i in "${group[@]}" do printf "%s\n" "$i" done
}

then for example

$ myfunc "one nine" "two" "three four five"
one nine
two
three four five

although in this particular case I don't see any benefit of the additional array variable - you may as well just loop over "$@" directly:

myfunc ()
{ for i in "$@" do printf "%s\n" "$i" done
}

If you just want it to "look like an array" in the calling context, then the only way I can think to do that would be to pass it as a string e.g. myfunc '("one nine" "two" "three four five")' and then eval the assignment inside your function eval group="$1" but I do not recommend doing that.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like