I want to process the file names with the whitespace, in steps: firstly ls them, then read the outputs one by one in the proper delimiter, then do else things. I know I have many different commands can be chosen, like find . -print0, or by changing IFS, but, specifically, on this matter, it seems that I have encountered a shell bug that I cannot figure out.
To reproduce:
# make a new empty folder
mkdir mytest
cd mytest
# create two files, one file name has the whitespace
touch 'nice 1' good
Create a new script file, the contents are:
#!/bin/bash
# to deal with filename contains whitespaces by using `array'
filetxt=()
ls | while read i; do
if [[ -f "$i" ]]; then
filetxt+=( "$i" )
# debug, inside works well
for ((t=0; $t<${#filetxt[*]}; t++)); do echo "-->${filetxt[$t]}<--"; done
echo '========='
echo ">>${#filetxt[*]}<<"
echo ''
echo ''
fi
done
# empty?? bug, cannot be dealt with
echo "last: >>${filetxt[*]}<<"
As my comment, can anyone please explain to me why ${#filetxt[*]} is empty outside the while loop? Yet, inside it, the code works well.
Is it due to the using of | (pipe) in the head of while loop, however, for bash, except from specifically defined, any variable will be in global status, thus, it should have contents stored in filetxt.
Moreover, my bash version is 5.0.17(1)-release (x86_64-pc-linux-gnu), I greatly appreciate for your help, many thanks.