Andrew Dryga
Andrew Dryga

Reputation: 692

What is the difference between escaping and quoting spaces in path?

Here is my code:

cp "./somepath/somefile.ext" ~/Library/MobileDevice/Provisioning\ Profiles/

echo "fail here"
ls -l ~/Library/MobileDevice/Provisioning\ Profiles/
echo "but success here"
ls -l "~/Library/MobileDevice/Provisioning Profiles/"

Why second ls returns ls: ~/Library/MobileDevice/Provisioning Profiles/: No such file or directory, when first one finds this dir?

Spent hours to debug this feature and can't understand the difference.

Upvotes: 0

Views: 347

Answers (3)

Alex Gidan
Alex Gidan

Reputation: 2679

It mostly depends on the command (read program) you're executing and how it handles the parameters you're passing.

This said, I would always prefer quotes when having to cope with spaces, as it's a more generic approach.

For instance, when using scp, you often would need to escape the second parameter twice, because it's escaped locally and then on the remote end:

scp [email protected]:"'a/b/My File a b c.xls'" .
scp [email protected]:a/b/My\\\ File\\\ a\\\ b\\\ c.xls .

As @that-other-guy said, careful to ~ expansion.

Upvotes: 0

chepner
chepner

Reputation: 531115

Very little. "a b" is essentially identical to \a\ \b. The backslash escapes the following character; quotes escape every character with in the quotes. Most of the time, an escaped character evaluates to the same character (\a is the same as a, because a has no special meaning).

The error you see is because tilde expansion only applies to unquoted ~. Your first ls should succeed, because ~ expands to your home directory. The second should fail because there is no directory literally named ~.

Upvotes: 2

that other guy
that other guy

Reputation: 123460

Let's ask ShellCheck:

In yourscript line 6:
ls -l "~/Library/MobileDevice/Provisioning Profiles/"
       ^-- SC2088: Note that ~ does not expand in quotes.

It goes on to explain that to combine ~ and quotes, you can just leave the ~ outside:

ls -l ~/"Library/MobileDevice/Provisioning Profiles/"

Upvotes: 2

Related Questions