5

I understand that one technique for dealing with spaces in filenames is to enclose the file name with single quotes: "'".

Why is it that the following code called, "echo.sh" works on a directory containing filenames with spaces, but the program "ls.sh" does Not work, where the only difference is 'echo' replaced with 'ls'?

echo.sh

#!/bin/sh
for f in *
do
echo "'$f'"
done

Produces:
'a b c'
'd e f'
'echo.sh'
'ls.sh'

But, "ls.sh" fails:

#!/bin/sh
for f in *
do
ls "'$f'"
done

Produces:
ls: cannot access 'a b c': No such file or directory
ls: cannot access 'd e f': No such file or directory
ls: cannot access 'echo.sh': No such file or directory
ls: cannot access 'ls.sh': No such file or directory

4
  • ls is looking for the names encased with single quotes and does not find them. e.g The file 'a b c' does not exist. Commented Mar 19, 2013 at 21:47
  • Then why does: ls 'a b c' work fine as a stand alone command? Commented Mar 19, 2013 at 22:26
  • The file 'a b c' does exist. so ls 'a b c' works. But the file ''a b c'' does not exist. Commented Mar 19, 2013 at 22:51
  • 1
    <a b c> exists, <'a b c'> does not exist. Not easy to type something about this quoting that is clear! Commented Mar 19, 2013 at 22:55

4 Answers 4

8

you're actually adding redundant "'" (which your echo invocation shows)

try this:

#!/bin/sh
for f in *
do
ls "$f"
done
Sign up to request clarification or add additional context in comments.

Comments

2

change the following line from

ls "'$f'"

into

ls "$f"

Comments

2

Taking a closer look at the output of your echo.sh script you might notice the result is probably not quite the one you expected as every line printed is surrounded by ' characters like:

'file-1'
'file-2'

and so on.

Files with that names really don't exist on your system. Using them with ls ls will try to look up a file named 'file-1' instead of file-1 and a file with such a name just doesn't exist.

In your example you just added one pair of 's too much. A single pair of double quotes" is enough to take care of spaces that might contained in the file names:

#!/bin/sh
for f in *
do
  ls "$f"
done

Will work pretty fine even with file names containing spaces. The problem you are trying to avoid would only arise if you didn't use the double quotes around $f like this:

#!/bin/sh
for f in *
do
  ls $f # you might get into trouble here
done

Comments

1

What about this ? =)

#!/bin/sh
for f in *; do
    printf -- '%s\n' "$f"
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.