Richard Stelling
Richard Stelling

Reputation: 25665

Problem Listing files in bash with spaces in directory path

When entered directory into the command line, this:

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

Prints a list of all the file ending in .png.

However when I try and 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 the error:

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

The space is causing an issue, but I don't know why?

Upvotes: 6

Views: 8217

Answers (4)

l0b0
l0b0

Reputation: 58768

Use more quotes and don't parse ls output.

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

Upvotes: 2

Yajushi
Yajushi

Reputation: 1185

you can try, [[:space:]] in place of space

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

or execute command to convert single space

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

Upvotes: 0

Michał Šrajer
Michał Šrajer

Reputation: 31182

Another option is to change 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

Read more about IFS in man bash.

Upvotes: 6

Michał Šrajer
Michał Šrajer

Reputation: 31182

If you fine with using while read and subprocess created by pipe, you can:

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

Upvotes: 1

Related Questions