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:
localsites+=('foo')
.localsites+=('foo') ; localsites+=("${newSite}")
localsites+=('foo') ; localsites+=("${newSite}")
. [*]
. 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.