7.24.2010

Filenames that contain spaces or special characters in linux

I am a long time windows user and for me it is normal to have spaces in directory and filenames. Changing to Linux I found myself frustrated when I moved my windows data over to my new Linux computer.
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 navigation for a 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.

There are two different ways I have found around this issue. I will explain them starting with the most simplest (in my opinion).

Quoting This is when you put a sting of text inside of quotes.
[root@bighat tmp]# 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
[root@bighat tmp]# cat 'filename with spaces'
OK NOW IT WORKS! :)

[root@bighat tmp]# 
As you can see when I use the command, cat filename with spaces, it presumed I was speaking of three different files not a single file with spaces in the name.
I corrected this by using quotes (' or ") with the command, cat 'filename with spaces', which tells linux to treat this text as one word (or treat the spaces as characters).

Another way to deal with 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 character:
[root@bighat tmp]# 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
[root@bighat tmp]# cat filename\ with\ spaces
OK NOW IT WORKS! :)

[root@bighat tmp]#