0

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.

Parsa Mousavi
  • 1,052
  • 1
  • 13
  • 31
  • 1
    Does this answer your question? [Reading filenames into an array](https://stackoverflow.com/questions/10981439/reading-filenames-into-an-array) – Shawn May 02 '20 at 18:36
  • Also see https://mywiki.wooledge.org/BashFAQ/020 – Shawn May 02 '20 at 18:45

1 Answers1

1

You can use newlines as IFS.

IFS=$'\n'
list_array=(`ls -p -m -1 . | grep -v /`)
lookat23
  • 26
  • 3