typeset -A is giving error in script

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 and grep, or using ${[email protected]} and a set of ordinary variables, which is available in older Bash versions. ${[email protected]} expands to the names of all variables whose names start with prefix, which you can use in combination with several variables prefix_key1, prefix_another to get most of the behaviours of associative arrays.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x