To an average Windows user it is normal to have spaces in directory and filenames. Beginner Linux users find it frustrating to deal with file names that contain spaces or special characters reserved for shell functions.

The problem occurs when at the command line. Although Linux does not care what you name a file, spaces and special characters cause problems when navigating in the shell. Spaces usually separate commands, the command arguments or multiple filenames. The shell in Linux does not know that all this text is one filename (e.g. My Documents). Also special characters already have a function within the shell (e.g. * is a wildcard) and they cause problems when used in a filename.

Use Quoting to Deal with Spaces and Special Characters in Filenames

There are two different ways to deal with this issue. I will explain them starting with the simplest (in my opinion), quoting. This is when you put a sting of text inside of quotes.

In this example we have a file called "filename with spaces". We are using the cat command to print the contents of this file. If we do nothing, the result is cat thinking we are providing three different files. This causes the following error:

$ cat filename with spaces
cat: filename: No such file or directory
cat: with: No such file or directory
cat: spaces: No such file or directory

If we wrap the name of the file in single quotes this signals the shell to treat it as a single string (treat the spaces as characters in the string).

$ cat 'filename with spaces'
OK NOW IT WORKS!

NOTE: Using single quotes will not allow variable expansion.

Escaping Spaces and Special Characters in Filenames

Another way to deal with spaces and special characters in a file name is to escape the characters. You put a backslash ( \ ) in front of the special character or space. This makes the bash shell treat the special character like a normal (literal) character.

We will use the same example, only this time escape the spaces instead of wrapping the whole string in quotes.

$ cat filename with spaces
cat: filename: No such file or directory
cat: with: No such file or directory
cat: spaces: No such file or directory

$ cat filename\ with\ spaces
OK NOW IT WORKS! 

Bash can (in some cases) automatically fix this for you. If you use tab completion bash will automatically escape the spaces for you.

Conclusion

This is a very simplified explanation of dealing with spaces and special characters in file names. It should be enough to give you a basic understanding of how to deal with them. There are other considerations like when to use double quotes vs single quotes. We will touch on these topics in later articles.