I am trying to collect in an array the names of the files existing in a folder. These names can contain whitespaces. Let us say that I have a folder "test" with two files:
aaa bbb.txt
ccc ddd.txt
I would like to write a bash script to get the following output:
"aaa bbb.txt"
---
"ccc ddd.txt"
---
I wrote the following bash script:
#!/bin/bash
cd "test"
readarray -t my_array < <(dir -Q -1)
for elem in ${my_array[@]}
do
echo "$elem"
echo "---"
done
cd ..
Regrettably, I get the following output:
"aaa
---
bbb.txt"
---
"ccc
---
ddd.txt"
---
It seams that the whitespace acts as a delimiter, but the documentation of the command readarray says that the default delimiter is the newline. How can this be explained?
This is not related to the readarray command itself but the way how Bash is splitting the text when you iterate over my_array[@].
($@) Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting.
see: source
To fix that you should put my_array[@] in quotes, so it doesn't treat space as delimiters there:
for elem in "${my_array[@]}"; do # <-- QUOTES ADDED HERE
echo "$elem"
echo "---"
done