Problem List of files in bash with spaces in directory path

When entering a directory on the command line:

ls -d -1 "/Volumes/Development/My Project/Project"/**/* | grep \.png$ 

Prints a list of all files ending with .png .

However, when I try to create a script:

 #! /bin/bash clear ; # Tempoary dir for processing mkdir /tmp/ScriptOutput/ ; wdir="/Volumes/Development/My Project/Project" ; echo "Working Dir: $wdir" ; # Get every .PNG file in the project for image in `ls -d -1 "$wdir"/**/* | grep \.png$`; do ... done 

I get an error message:

 cp: /Volumes/Development/My: No such file or directory 

space is causing a problem, but I don't know why?

+4
source share
4 answers

Another option is to change the IFS:

 OLDIFS="$IFS" # save it IFS="" # don't split on any white space for file in `ls -R . | grep png` do echo "$file" done IFS=$OLDIFS # restore IFS 

Learn more about IFS in man bash .

+5
source

Use more quotes and don't parse ls output .

 for image in "$wdir"/**/*.png; do 
+2
source

If you're comfortable using while read and a subprocess created by pipe, you can:

 find . -name '*.png' | while read FILE do echo "the File is [$FILE]" done 
0
source

you can try, [[: space:]] instead of space

 wdir="/Volumes/Development/My[[:space:]]Project/Project" 

or execute a command to convert a single space

 wdir=`echo "$wdir" | sed 's/[[:space:]]/\[[:space:]]/g'` 
0
source

All Articles