I want to use associative array in zsh, but it doesn't work.

Asked 1 years ago, Updated 1 years ago, 256 views

I write a shell script with macOS zsh, but there are many samples on the Internet that use the -A option when using the associative array (declare command), but when I actually use it, I am told that the option does not exist.

In addition, keys from 1 to 9 are referenced, but 0 or alphabetic keys are not referenced, and the last element is referenced.

Based on the above, I would like to know the following two points.

The actual sources are as follows:

declare sample=(
    ['1']="100 100"
    ['2']="200 200"
    ['3']="300 300"
    ['4']="400 400"
    ['5']="500 500"
    ['6']="600 600"
    ['0']="00000 00000"
    ['A'] = "AAAAAAAAAAAAAAAA"
    ['B'] = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
)

echo${sample['1']}
echo${sample['2']}
echo${sample['3']}
echo${sample['4']}
echo${sample['5']}
echo${sample['6']}
echo${sample['0']}
echo${sample['A']}
echo${sample['B']}

Run Results

100 100
200 200
300 300
400 400
500 500
600 600
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB

macos shellscript zsh

2022-09-30 21:55

1 Answers

The version of Mac bash is low, so download and install 5 series from brew. You must create a shell script with #!/usr/local/bin/bash.
If there's a blank space, it won't work well with the old bash of Mac 3.

Alternatively, you must create an associative array with typeset-A in zsh.


2022-09-30 21:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.