How do you read a command's output into an array correctly?
IntermediateConceptArrays, conditionals and loops
Answer
Use mapfile (alias readarray), which splits on newlines only:
mapfile -t pods < <(kubectl get pods -o name)
echo "found ${#pods[@]} pods"
# NUL-delimited for arbitrary filenames (Bash 4.4+)
mapfile -d '' -t files < <(find /var/log/app -name '*.log' -print0)
Avoid arr=( $(cmd) ): it splits on spaces and expands globs, so a line * 2 pods becomes a directory listing. ShellCheck flags this as SC2207.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?IntermediateList the most-used file test operators.Beginner