How to Read a Filename With Spaces in Linux?

In Linux, users can include spaces between the filename while creating or editing files. However, spaces in filenames can cause issues when working with the command line because the shell interprets spaces as delimiters between arguments. To overcome this, Linux offers various ways to read a filename having spaces. 

This blog will provide several methods for reading a filename along with spaces in Linux. 

Method 1: Using Quotes to Read a Filename Along with Spaces

An existing file having the name “my file.txt” is considered to display its content using the command “cat“. Before it, users need to enclose the filename in quotes as below:

$ cat "my file.txt"

This above command tells the shell to treat the entire string “my file.txt” as a single argument rather than interpreting the space as a delimiter between “my” and “file.txt“.

Method 2: Using Backslashes to Read the Filename Having Spaces

Users can utilize the backslashes (\) to escape the spaces to read the filename. In our case, specify the “my\ file.txt” filename with the “cat” command as below: 

$ cat my\ file.txt

The output confirms that the “my file.txt” has been successfully read with spaces in the terminal.

Note: Users require one backslash for each space if the filename contains three or more words.

Method 3: Using Tab-Completion to Read a Filename with Spaces

Another way to handle filenames with spaces is to utilize the tab-completion feature that the shell provides. By hitting the “tab” key twice in a row, the shell will display the available options that match what you have typed so far. 

In our case, we type “cat my” and the shell automatically completes the filename “cat my\ file.txt” as below:

$ cat my<tab><tab>

The output shows that after pressing the “tab” key twice, the script is completed to read the filename “my file.txt” and display content in the terminal.

Conclusion

Linux offers the “quotes”, “backslashes”, and “tab-completion” methods to read a filename with spaces in a specified directory. The most convenient and recommended method is using the quotes around the filename. This post has addressed the practical implementation of all these methods.