Search code examples
bashassociative-arraymacos-mojave

Using associative arrays in a bash script on MacOS


I am using MacOS ( Mojave 10.14.6 ) and trying to write a bash script. I have installed latest version of bash - 5.0.16(1)-release (x86_64-apple-darwin18.7.0) - using brew install.

I do not have access to update the /etc/shells file, so I tried using

#!/usr/bin/env bash
bash --version

in my script's code

And that also returns the above version - 5.0.16(1)-release (x86_64-apple-darwin18.7.0) -, but when, in the same script, I try

declare -A svcCount

I get the below error

declare: -A: invalid option
declare: usage: declare [-afFirtx] [-p] [name[=value] ...]

which seems to indicate, the script is still using the the default bash version 3.x from Mac.

How should I change the script so that I can use the above construct of associative array definition?

Thank you


Solution

  • Please save this as theScript if you want to use the homebrew bash:

    #!/usr/local/bin/bash
    echo $BASH_VERSION
    declare -A svcCount
    

    Then make it executable with:

    chmod +x theScript
    

    and run with:

    ./theScript