Reputation: 32
While writing a bash script I've encountered a strange problem: one array with a specific name has an unpredictable length, which somehow depends on its input. All the other arrays behave correctly. This is what I can observe:
Maybe it's some kind of memory allocation error, because there existed a variable with the exact same name which was NOT an array.
Here are some examples of the strangeness:
original input
ARRAY=(a b d f k l)
bash output
$ bash setup-env.sh
Array:
a
original input
ARRAY=(asdfasdf1 asdasdf2 asdfasdf3 asdfasdf4 asdfasdf5 asdfasdf6 asdfasdf7 asdfasdf8)
bash output
$ bash setup-env.sh
Array:
asdfasdf1
asdasdf2
asdfasdf3
asdfasdf4
asdfasdf5
asdfasdf6
asdfasdf7
asdfasdf8
original input
ARRAY=(ASD1 ASD2 ASD3 ASD4 ASD5 ASD6)
bash output
$ bash setup-env.sh
Array:
ASD1
ASD2
ASD3
ASD4
original input
ARRAY=(1asdf asdf)
bash output
$ bash setup-env.sh
Array:
1asdf
asdf
I'm curious as to why this happens
EDIT: setup-env.sh
:
#!/bin/bash
export FOLDER_NAME=(1asdf asdf)
echo "Array: "
for ((i = 0; i < ${#FOLDER_NAME}; i++)); do
echo "${FOLDER_NAME[i]}"
done
#. "write.sh"
The strange array in question is FOLDER_NAME
. It's supposed to be exported for further use. Right now I can't use it, because it behaves unexpectedly.
Upvotes: 1
Views: 75
Reputation: 1327
I see your problem. You're using
${#FOLDER_NAME}
while the correct way is
${#FOLDER_NAME[@]}
this is because if you have
ARRAY=(verylongstring basd ddf)
the output of echo ${#ARRAY}
will be the lenght of the first variable.
The way to do it is:
for i in ${ARRAY[@]}; do echo $i; done
it works as expected.
Upvotes: 0
Reputation: 183574
Judging from your example output, your code is supposed to use the number of elements in the array, but is instead using the number of characters in the first element in the array.
The most likely cause is that you've written ${#ARRAY}
instead of ${#ARRAY[@]}
. If you fix that, it should work.
In the future, however, please be sure to include the relevant code in your questions here. Today I managed to be psychic (assuming I'm right), but that's obviously not something you can rely on!
(Incidentally, you don't even need ${#ARRAY[@]}
to print the elements of the array; you can just write printf '%s\n' "${ARRAY[@]}"
or for elem in "${ARRAY[@]}" ; do echo "$elem" ; done
.)
Upvotes: 2