1

Im trying to make a script that should be executed with crontab, but I'm having difficulties to declare an array an fetch the key and value from that array. (Running MacOS 10.12.6)

This is what i'v got so far:

#!/bin/bash

declare -A listofnames

listofnames[one]="one test"
listofnames[two]="two test"

for val in "${listofnames[@]}"; do
    echo $val
done

And this throws me an error: declare: usage: declare [-afFirtx] [-p] [name[=value] ...] and the output it two test.

Expected output:

$ ./test.sh
one test
two test
  • Come on, folks…don't downvote without an explanation. – TJ Luoma Jul 18 at 18:22
  • 1
    macOS comes with bash version 3 (for licensing reasons), but associative arrays weren't added to bash until version 4. If you can't do what you need with numerically-indexed arrays, your best bet would be to install bash v4 with homebrew, and then change the shebang line to use it instead of the built-in version. – Gordon Davisson Jul 18 at 18:26
  • What version of macOS are you running? – Allan Jul 18 at 18:35
  • 1
    @GordonDavisson Nice! Seems that I have bash 5 installed, just changed the shebang and everything works smoothly now. – Adam Jul 18 at 18:38
1

It's not required that you declare your array upfront, but if you do, you need to use the lower case "a"; not the capital.

declare -a listofnames

Secondly, you need to use numerical indicies when referencing an array element

listofnames[one] <----- incorrect
listofnames[1]   <----- correct

So, for your two elements, it should look like this:

listofnames[1]="one test"
listofnames[2]="two test"

Or you assign all values at once, taking care of the first element having index 0

listofnames=("", "one test", "two test)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .