I was using associative arrays in my script, hence I used to declare them by the
typeset -A <array_name>
command, and it worked fine in the bash prompt
But when I use it in my script, I get the following error
typeset: -A: invalid option
typeset: usage: typeset [-afFirtx] [-p] name[=value] ...
An alternative solution will also be acceptable for me.
SIDENOTE: I tried typeset -a but it declares an indexed array. But I want an associative array.
Best Answer
That is the error generated by Bash 3 for
typeset -A
. Associative arrays were added in Bash 4, and are not in Bash 3.2 and earlier.It seems that your script is being run with a different version of Bash than you are using as your shell. If you're on the same machine in both cases, you have multiple versions installed and can probably select one with a different path. If you're on a different machine running the script, you may be able to install a newer version, but otherwise you're out of luck for direct support in Bash.
zsh
supports associative arrays since much older versions, so if you have that available you can likely port your script without too much work. If you're unable to do that, you can fake it with regular arrays andgrep
, or using${!prefix@}
and a set of ordinary variables, which is available in older Bash versions.${!prefix@}
expands to the names of all variables whose names start withprefix
, which you can use in combination with several variablesprefix_key1
,prefix_another
to get most of the behaviours of associative arrays.