I have the following code:
filelist="$(find $name -type f | sort)";
echo "$filelist";
echo "${#filelist[@]}"
My array contains many elements but the last command says my array contains only one element. What am I doing wrong?
Getting the array length To get the length of an array, we can use the {#array[@]} syntax in bash. The # in the above syntax calculates the array size, without hash # it just returns all elements in the array.
We can use the # operator to get the length of the string in BASH, we need to enclose the variable name enclosed in “{ }” and inside of that, we use the # to get the length of the string variable. Thus, using the “#” operator in BASH, we can get the length of the string variable.
`expr` command can be used by two ways to count the length of a string. Without `expr`, `wc` and `awk` command can also be used to count the length of a string.
You need to use parentheses to have bash recognize it as an array.
filelist=($(find $name -type f | sort))
echo ${#filelist[@]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With