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.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Linux system queries.
In this context, we shall look into 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 below:
$ touch 'name of the file'
For example, we shall create a file called linuxapt docs 2021 as follows:
$ touch 'linuxapt docs 2021'
Next, we will add some content to the file:
$ echo "Welcome to Linuxapt" >> 'linuxapt 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 linuxapt\ 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/
[Need assistance in fixing Linux system issues? We can help you. ]