1

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.

2 Answers 2

3

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 ${!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 with prefix, which you can use in combination with several variables prefix_key1, prefix_another to get most of the behaviours of associative arrays.

4
  • Hi Michael, will zsh 4.2.6 (x86_64-redhat-linux-gnu) support associative arrays? Commented Aug 13, 2014 at 9:04
  • zsh has had associative arrays since version 4 (released 2001), so they should be fine. Commented Aug 13, 2014 at 9:08
  • Hi Michael, for the following statement for KEY in ${!array[@]} zsh is giving bad substitution error. Any idea why? Commented Aug 13, 2014 at 9:41
  • See man zshexpn for the details of zsh parameter expansion. Otherwise, asking a new question about zsh will get more attention from others too. Commented Aug 13, 2014 at 9:47
0

I was able to resolve the issue by using this shebang as the first line of the script

#!/bin/zsh

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.