I have the following bit of code in a bash script I've created. When I run it from a directory with no spaces in the path it works as expected, however if I run from a directory with spaces it fails. I'm pretty sure I need to escape it somehow, but nothing I've tried seems to work.

for file in `pwd`/*
    echo file:$file

By 'fails' I mean that if I run the command from the path "~/dir 1/ test" it would echo the following:

file: ~/dir
file: 1/
file: test

I'd expect it to list the files in the directory (which it does if there's no spaces in the current directory):

file: file 1
file: file 2
file: file 3

Note this is only an issue if the current directory has spaces in, files with spaces in are processed fine.

I've read several similar examples on here such as Why does my shell script choke on whitespace or other special characters? and Looping through files with spaces in the names? but I can't see how (if they are relevant) they apply to my specific example.


1 Answer 1


Thanks to Paulo Tomé I needed to change it to the following:

for file in "$(pwd)"/* 
    echo file:"$file" 

Not the answer you're looking for? Browse other questions tagged or ask your own question.