0

I am trying to add folder paths to an array. I looked up on the internet and saw this solution. I gave it a try but I get an error message.

My code:

LOCALSITES=()

for d in "$DIRLOC"/*; do
    ${LOCALSITES}+='foo'  #doesnt work
done

echo "${LOCALSITES[*]}"

Error message:

showSites.sh: line 35: +=: command not found
  • 1
    Don't use `$` or `{}` when assigning to a variable (or array); that's to *get* its value(s). Do use parentheses to add elements, and double-quote the thing being added to avoid possible weird parsing. Finally, it's best to use lower- or mixed-case variable names to avoid conflicts with the many all-caps vars with special functions. Thus: `localsites+=("$d")`. Oh, and you almost never want `[*]` -- use `[@`] instead (and double-quotes around it): `echo "${localsites[@]}" – Gordon Davisson Mar 22 '20 at 23:13
  • @Gordon, putting what should be an answer in a comment is almost (but not quite) as problematic as commenting in an answer. I don't believe comments are indexed for searches in the same way answers are, so they're pretty much useless in terms of helping *future* searchers out, one of the main reasons for SO. It would be far better off were you to answer as an answer! For now, I've incorporated them into the accepted answer. – paxdiablo Mar 22 '20 at 23:32

1 Answers1

0
${LOCALSITES}+='foo'

will interpret the current value of that variable, giving you an empty string and therefore making the command read as:

+='foo'

You can see this if you do set -x beforehand:

pax:~$ set -x ; ${xx}+='foo' ; set +x
+ set -x
+ +=foo
+ '[' -x /usr/lib/command-not-found ']'
+ /usr/lib/command-not-found -- +=foo
+=foo: command not found
+ return 127
+ set +x

It's no real different to:

pax:~$ xx=1
pax:~$ ${xx}=2 # should be xx=2
1=2: command not found

To properly append to the array, you need to do:

LOCALSITES+=('foo')

Other things you may want to consider, courtesy of one Gordon Davisson in a comment:

  • It's probably best to use lower- or mixed-case variable names to avoid conflicts with the many all-caps variables with special functions: localsites+=('foo').
  • Make sure you select the correct quotes for whether you wish to interpret variables or not: localsites+=('foo') ; localsites+=("${newSite}").
  • You almost never want [*]. Use [@] instead, and put double-quotes around it: echo "${localsites[@]}".
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953