Best Practice for Escaping Pathnames: "" or \ ?

dstranathan
Valued Contributor II

Just curious: Are you a backslasher or a quoter? Example:

Quotes:
if [[ -f "/Volumes/Macintosh HD/Library/Preferences/com.apple.file.plist" ]]; then rm -f "/Volumes/Macintosh HD/Library/Preferences/com.apple.file.plist"
fi

OR

Backslashes:
if [[ -f /Volumes/Macintosh HD/Library/Preferences/com.apple.file.plist ]]; then rm -f /Volumes/Macintosh HD/Library/Preferences/com.apple.file.plist
fi

Personally, I prefer a (backslash) to escape spaces in file names and paths. Not sure why (been doing it for years). Some prefer quotes because they are easier to see.

Is there a best practice or style guide for this? Opinions?

4 REPLIES 4

mm2270
Legendary Contributor III

I use quoting almost all the time for stuff like this. I do it even for paths that (should) contain no spaces in them or odd characters. Mostly I do this because since I tend to use a lot of dynamically generated variables in scripts, quoting makes far more sense since you really don't know what you may run up against in those scenarios, and in fact it would be pretty difficult to use the backslash syntax if its being set on the fly.

Also, backslashes are needed for more than just spaces. For example, take a file name like-

One&Two.txt

Despite there being no space in it, it would actually need to be written like:

One&Two.txt

to escape the & symbol. But if double quoting it, you can write it like:

"One&Two.txt"

and you're OK. That's only one example. Several other non space characters also need to be backslash escaped to work properly without double quotes around them.

To each his own of course, and the answer to your question is just that, there is no right answer, only preference. But for me, double quoting is safer and less prone to errors in the long run.

Look
Valued Contributor III

I just like the way quotes read better than back slashes. Especially if you have multiple characters requiring escaping which just end up looking like your trying to type some kind of weird emoji!

AVmcclint
Honored Contributor

I'm a quote guy myself. However, I have encountered situations where I need to state a file that already has quotes in the name.

"this filename"

means the file name is exactly:

"this filename"

JPDyson
Valued Contributor

If I'm doing it on purpose, I quote it.

Only time I really ever use a is if I'm typing in a path in the shell (never in scripts, as a practice).