This write-up is focussing on what errors we face while accessing files and directories with space in their names and how to avoid such errors.
How to create a file with spaces in its name in Linux
To understand how to reference a filename with spaces in Linux, we will consider an example. First, we will open the terminal. Then create a file with the name “my file” by using the touch command: Now see the file is being created or not by using the “ls” command. We observed that instead of one, two files have been created, one with “my” and the second with the “file” name. To use spaces in the name we use either quotes (‘ ’) or escape sequence (). Now we again make another file using (‘ ’) and another using (). Now again use the “ls” command to view files. Files have been created. Let’s check if we get the same errors in the creation of a directory using space or not. We will create a directory using space with the mkdir command. We will view whether the directory has been created or not using the “ls ” command. It created two directories instead of one. We can rectify this in the same way as we did in the file creation method by using (‘ ‘) or (). Again make a directory using this (‘ ‘) or (). Now we will check out the results.
How to reference filename with spaces in Linux
So we can see that the directory has been created according to our requirements. Now if we want to view the contents of the file, we simply use cat and file name with spaces; it will give us an error that the directory is not available. We should use “\”. For example, we want to view the contents of a test file by using the cat command. The file is empty so it displays no results but the command runs successfully. We can also open files by using apostrophes (‘ ’) or quotations (“ ”) as:
Delete filenames with Spaces in Linux
Similarly, you can also delete a file and directory with space in their name by using apostrophes ( ‘ ’ ), quotation marks (“ ”) or escape sequence ( \ ). Similarly, you can delete a directory with spaces in the name.
Conclusion
We create files and directories, without bothering to focus on the names that can have spaces. The Linux terminal treated files and folders differently that have spaces in their names. So this article solved the problem. If we want to name a file or directory with spaces we can do it by using apostrophes ( ‘ ’ ) , quotation marks (“ ”) or escape sequence ( \ ).