1

I have a script that has a couple of arrays in it. I didn't want to repeat counting the array size so I tried to create a function that does it for me. I'm passing the function the name of the array whose size I want. It runs through the function until it finds an empty space and then returns the count. This is my function:

array_size ()
{
    # Calculate the size of your array
    count=0
    while [ ${$1[$count]} != "" ]
    do
         count=$(( $count + 1 ))
    done

    #Subtracts 1 from count to reset array position
    count=$(( $count - 1 ))

    return $count

}

I get the following error when I call this: ${$1[$count]}: bad substitution. How can I pass the array name to this function?

3
  • 7
    Why are you not using the capabilities built into bash (i.e. ${#array[@]})? Commented Sep 24, 2018 at 15:00
  • 1
    Additionally, the array ('' 1 2 3) would be considered to have length zero by your function. Commented Sep 24, 2018 at 15:11
  • 1
    It also wouldn't be able to deal with arrays with non-contiguous indices: arr[1]=x has no index 0. Commented Sep 24, 2018 at 15:13

1 Answer 1

2

(Note, in these examples, I haven't implemented your counting logic.)

With a recent bash (starting from version 4.3 I think) you can use a nameref:

$ declare -a main
$ main[4]=a main[6]=b main[11]=c
$ declare -p main
declare -a main='([4]="a" [6]="b" [11]="c")'
$ aryfunc () { 
    local -n ary=$1
    for key in "${!ary[@]}"; do
        printf "%d => %s\n" "$key" "${ary[$key]}"
    done
}
$ aryfunc main
4 => a
6 => b
11 => c

Otherwise, you can use indirect variables, but you lose the indices:

$ aryfunc2() {
    local tmp="${1}[@]"
    local -a localary=( "${!tmp}" )
    for key in "${!localary[@]}"; do
        printf "%d => %s\n" "$key" "${localary[$key]}"
    done
}
$ aryfunc2 main
0 => a
1 => b
2 => c

Or if you want to get really gross, pass the definition of the array:

$ aryfunc3() {
    local declaration="$1"
    eval local -a localary="${declaration#*=}"
    for key in "${!localary[@]}"; do
         printf "%d => %s\n" "$key" "${localary[$key]}"
    done
}
$ aryfunc3 "$(declare -p main)"
4 => a
6 => b
11 => c
Sign up to request clarification or add additional context in comments.

Comments

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.