command line - Pass array to function parameter in terminal inside for loop - Ask Ubuntu


i have following code:

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

i using print every item in group array. array should parameter in terminal. when try use in terminal inside .bash_profile file doesnt work. trying running following command:

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

you seem expecting shell generate kind of anonymous array variable - afaik that's not possible in bash.

the simple approach pass individual arguments (which may contain whitespace, if quoted) , refer them "$@"

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

then example

$ myfunc "one nine" "two" "three 4 five" 1 9 2 3 4 5 

although in particular case don't see benefit of additional array variable - may loop on "$@" directly:

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

if want "look array" in calling context, way can think pass string e.g. myfunc '("one nine" "two" "three 4 five")' , eval assignment inside function eval group="$1" not recommend doing that.


Comments

Popular posts from this blog

download - Firefox cannot save files (most of the time), how to solve? - Super User

windows - "-2146893807 NTE_NOT_FOUND" when repair certificate store - Super User