How to deal with spaces in file names

When doing anything from the command line, like using Mac's Terminal or running commands in Linux, dealing with spaces can be problematic.

Spaces function as a separator so something coming after a space will be treated as an independent entity across unix-based systems, like Mac and Linux. For example, if there were a folder named "Open Active" and you wanted to navigate inside using the cd command, you might be tempted to type:

cd Open Active

However, this only tells the machine to try to navigate inside a folder called "Open" in the current directory while "Active" sort of hangs off to the side like a sixth toe. Assuming you don't have a folder called "Open," you'll probably get a message something like this:

-bash: cd: Open: No such file or directory

What gives? It's that pesky space. Rather than rename your directory, there are a couple of easy ways to deal with this little problem.

Quoting

My favorite for its utter simplicity and universal applicability is to simply put file names in single quotes (') like this:

cd 'Open Active'

Single quotes is pretty much a universal way to tell a machine to deal with what's inside of the quotes just the way it is, not to do any fancy stuff.

Escaping

There is another method you should be aware of which is also a great way to deal with a whole variety of scenarios beyond spaces, but works for spaces as well, which is to use the backlash (\) as an escape. What this does is tells the machine to deal with the next character just the way it is, not to do any fancy stuff.

So, you can also deal with the aforementioned space in the file name problem like this:

cd Open\ Active

The reason that it's not quite as elegant is that if you have a directory or file name that has a lot of spaces, you'll need to do a lot of escaping. For example, if you wanted to remove a file (using the rm command) called "general instructions for how to escape a blank space.txt" You would have to escape 9 times:

rm general\ instructions\ for\ how\ to\ do\ escape\ a\ blank\ space.txt

Irritating right? Life is much easier when you just do the following:

rm 'general instructions for how to do task x.txt'

That's all there is to it. With these two arrows in your quiver, you can defeat spaces in file and directory names without breaking a sweat.