bash - Adding value to array passed as an argument doesn't add value to it -


when try pass array parameter , add value it, end's being empty @ end.

how add value passed array? make array global, passing different arrays, must passed function parameter.

#!/bin/bash  base='/home'  declare -a files_new declare index  arrayit() {     #$1 = path     #$2 = array      dir=($1/*)     arr=$2      directory in "${dir[@]}"             if [[ -d $directory ]]                     arrayit $directory $arr         else             arr[$index++]=$directory         fi     done }  index=0 arrayit $base $files_new  file in "${files_new[@]}"     echo "file: $file" done 

passing around arrays in bash real pita. i've found reliable method

$ ary=(foo bar baz) $ fn() { local tmp="${1}[@]"; local copy=("${!tmp}"); declare -p copy; } $ fn ary declare -a copy='([0]="foo" [1]="bar" [2]="baz")' 

that gives copy in function. changes made in function not appear in parent scope.

however, bash version 4.3 has "name references"

$ fn() {      local -n myary=$1       # note: -n -- see "help declare"     declare -p myary     key in "${!myary[@]}"; printf "%s\t%s\n" "$key" "${myary[$key]}"; done     myary[42]="new value" } $ fn ary declare -n myary="ary" 0   foo 1   bar 2   baz $ declare -p ary declare -a ary='([0]="foo" [1]="bar" [2]="baz" [42]="new value")' 

note new value in parent scope! hooray!


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -