In Linux and UNIX systems, it’s always recommended against having directories and files with spaces. Handling directories and files with spaces can be annoying and the risk with spaces in files is that they can easily be misinterpreted by applications. Some scripts and programs can break when presented with filenames with spaces in them. It’s for this reason that there are naming conventions such as in web files and downloadable files which are hosted on a web server.
Regardless, you are still bound to come across some files with spaces between them, for example, docker tutorials instead of docker-tutorials. In this guide, we will walk you through how you can read a filename with spaces in a Linux system.
How to create and read a file with spaces
Before we can explore how to read a file that contains spaces, let us see how we can create one to begin with.
To create a file with spaces, enclose the filename inside double single quotes as shown.
$ touch ‘name of the file’
For example, we shall create a file called linuxways docs 2021 as follows:
$ touch ‘linuxways docs 2021’
Next, we will add some content to the file.
$ echo “Welcome to Linuxways” >> ‘linuxways docs 2021’
To read the file, use the cat command to view the file while adding a backslash at the end of every name and a space before the next word.
$ cat linuxways\ docs\ 2021
An easy way is to invoke the cat command, type the first few letters and press TAB to autocomplete. Your Linux system is smart enough to detect the filename and place the backslashes and spaces between the file names.
How to create and access a directory with spaces
To create a directory with spaces, use the mkdir command with a backslash at the end of every name with a space separating it and the next name. In the example below, we have created a directory called marketing reports 2021.
$ mkdir marketing\ reports\ 2021
To navigate into the directory, use the cd command and type the directory name with the same format as demonstrated before.
$ cd marketing\ reports\ 2021
Any other operation involving the directory will require you to use the same format of inserting backslashes after every word.
For example, to copy the directory to another directory, for example, the /opt directory, run the command:
$ sudo cp -R marketing\ reports\ 2021 /opt/
While it’s generally a bad idea to create files with spaces between them, you will occasionally bump into them and this may present unique challenges. In this walkthrough, we have presented ways that you can read such files and also handle directories with filenames that contain spaces.
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.