简体   繁体   中英

'+=: Command not found' when trying to add a value to an array - Shell Script

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
${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}") localsites+=('foo') ; localsites+=("${newSite}") .
  • You almost never want [*] . Use [@] instead, and put double-quotes around it: echo "${localsites[@]}" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM