I want to write a bash script and I need to get the filenames in a directory and I've done this :
list=`ls -p -m -1 $dir | grep -v /`
list=`echo $list | tr ' ' ','`
IFS=',' read -ra list_array <<< $list
If no file with whitespaces in the current directory exists , then the variable list_array
holds the correct space-seperated array of filenames :
$ echo "${list_array[*]}"
a a.rar a.tar a.zip blah blah blah
But that wouldn't work correctly in situations where there exists some files with whitespaces in their names.To mitigate this , I changed that as follows :
list=`ls -p -m $dir | grep -v /` #This doesn't work in for filenames without whitespace
IFS=',' read -ra list_array <<< $list
But now list_array
only holds the name of the first file.
Any help is greatly appreciated.