I've been trying to run a simple script that retrieves the penultimate subdirectory of a variable size directory. But it fails miserably to retrieve its length. The script goes:
ARRAY=$(ls files-0/var/log/)
echo ${#ARRAY[@]}
for i in ${#ARRAY[@]};
do
echo $i
done
The output I get is:
1
1
If i change the line
for i in ${#ARRAY[@]};
by
for i in $ARRAY;
at least I get the list of directories/files:
53513
53514
53515
...
I know there are lot's of posts approaching this question, but mostly all of them start from the basis of getting array length properly.
Best How To :
Following up on the comment, the syntax for initializing indexed array values in BASH is:
array=( element1 element2 etc... )
In your case you were simply assigning the result of the command substitution to the array with:
ARRAY=$(ls files-0/var/log/)
(which assigned the return of ls files-0/var/log/
to a variable named ARRAY
)
The proper initialization of the ARRAY
using command substitution is:
ARRAY=( $(ls files-0/var/log/) )
Note: when an array is declared with declare -a somename
, or after it has been initialized with values, you can add an element to the array in the next open index with:
ARRAY+=( somevalue ) # quoted as necessary
As of BASH 4, you also have Associative Arrays
(declare -A) which allow arrays to be created with key
value
pairs, instead of simple index
value
pairs. Where initialization is:
AARRAY=( [key1]=value1 [key2]=value2 etc... )
Good luck with BASH, it is a very capable shell.