1. Introduction

In this tutorial, we'll see how to delete a file whose name begins with "-" using the rm and find commands. Additionally, we'll explain their similarities with some useful examples.

2. Input Files

We'll use the same input files for all our examples, so let's create a folder called baeldung and run the following command to create some files:

$ touch -- -baeldung.txt test.txt file_name.txt baeldung.txt

So using the above, we've created four txt files, where -baeldung.txt will be our target throughout this tutorial.

And, if we're successful, by the end of this tutorial, the baeldung folder will have only three files instead of four:

$ ls baeldung
baeldung.txt	file_name.txt	test.txt

3. Using rm

rm is a very popular command to delete files and directories in Linux operating systems. We'll start by focusing on this command to achieve the described target of this tutorial.

A feature of rm is the double-dash, "--", which means that no command-line options will follow after itWhile optional in most circumstances, it'll come in handy in this case.

Imagine if we tried to delete -baeldung.txt like any other file:

$ rm -baeldung.txt

The issue here is that rm will think that "baeldung.txt" is a command-line option like -r or -f.

So let's instead run rm with the double-dash, so that it knows that nothing to the right of it is a command-line option:

$ rm -- -baeldung.txt

As we can observe, we aren't getting any error because we're using "--" before the name of the file, preventing the interpreter from accepting more command-line options.

4. Using find

As we've seen in the previous section, it's very easy to get an error if we forget to specify "--" before -baeldung.txt. So, let's see another method that might be more user-friendly.

find is another one of the more famous commands in Linux operating systems. It allows us to search for files using patterns and execute an operation afterward.

If we run the following command, we'll get the same result as with rm. But as we can see below, there are two steps.

First, we search for the desired file, in this case -baeldung.txt. And second, we perform the delete action using the -delete option:

$ find . -name '-baeldung.txt' -delete

5. Conclusion

In this tutorial, we've explained two different ways to delete a file whose name starts with "-" from the current working directory using the rm and find commands.

As we've seen in the above examples, the find command is more intuitive to the naked eye than rm. Be sure to check out the vast array of operations find supports at the appropriate man page.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments