I am trying to define array in my shell script which would have content like below

cassandra_hosts=(cassandra1.test-dev.local cassandra2.test-dev.local cassandra3.test-dev.local)

But it doesn't let me define it and gives error as below.

-bash: syntax error near unexpected token `cassandra1.test-dev.local'

I tried below combinations to define it but they didn't work.

cassandra-hosts=('cassandra1.test-dev.local' 'cassandra2.test-dev.local' 'cassandra3.test-dev.local')
cassandra-hosts=("cassandra1.test-dev.local" "cassandra2.test-dev.local" "cassandra3.test-dev.local")
cassandra-hosts=(cassandra1\.test-dev\.local cassandra2\.test-dev\.local cassandra3\.test-dev\.local)
cassandra-hosts=('cassandra1\.test-dev\.local' 'cassandra2\.test-dev\.local' 'cassandra3\.test-dev\.local')
cassandra-hosts=("cassandra1\.test-dev\.local" "cassandra2\.test-dev\.local" "cassandra3\.test-dev\.local")
cassandra-hosts=("cassandra1\.test-dev\.local" "cassandra2\.test-dev\.local" "cassandra3\.test-dev\.local")
cassandra-hosts=('cassandra1\.test-dev\.local' 'cassandra2\.test-dev\.local' 'cassandra3\.test-dev\.local')

What am I doing wrong?

  • The syntax of your original command is correct; the others that use quotes but not escapes are also correct. Something else has to be causing the problem, but I don't know what it might be. Commented Aug 7, 2018 at 14:50
  • 2
    I figured it out. we can not have a hyphen character - in array name. Commented Aug 7, 2018 at 17:18

1 Answer 1

bash-4.2$ cassandra_hosts="cassandra1.dev-internal.local cassandra2.dev-internal.local cassandra3.dev-internal.local"
bash-4.2$ for i in $cassandra_hosts; do echo "host: $i"; done
host: cassandra1.dev-internal.local
host: cassandra2.dev-internal.local
host: cassandra3.dev-internal.local
  • 2
    Note that this doesn't define an array, just a string that happens to contain multiple space-delimited words. This approach will work as long as the items don't contain whitespace or wildcards; if they do, things will get weird. You can probably get away with a string in this case, but I'd still recommend trying to figure out why an array isn't working rather than give up on them. Commented Aug 7, 2018 at 14:52

You must log in to answer this question.

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