简体   繁体   中英

Problem getting an array of filenames which contain whitespaces in Bash

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.

You can use newlines as IFS.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM