How to access or remove files with leading dash in filenames on Linux

Some Linux tools generate file with leading dash or hyphen ("-") in filenames. Or your hand-written program can accidentally produce filenames starting with minus. If you attempt to remove, copy, rename, or otherwise access such files by using ls, rm, cp, mv or chmod, you will get the following errors.

[cmd]: invalid option --

That is because your Linux system interprets the leading minus in filename as part of command line option, and throws an invalid option or non-existent mode error.

In order to deal with a leading dash in filename under Linux shell, you can try one of the following two methods.

Method one

Since a leading minus in filename introduces ambiguity in recognizing the filename, you just need to eliminate such ambiguity by prepending a pathname to the filename. For example, if you have a file named "-my.txt" in current directory, you can access it as follows.

$ chmod 600 ./-my.txt
$ rm ./-my.txt

Method two

The second method to deal with a leading hyphen character is to take advantage of a special argument "--" which is interpreted by getopt() as the "end of option." Most standard Linux command line utilities use getopt() to process command line arguments. When getopt() encounters "--", it stops option-scanning process. Therefore, just insert "--" in front of the filename to make it explicit that the hyphenated filename is not part of command line arguments.

$ chmod -- 600 -my.txt
$ rm -- -my.txt

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.
Your name can also be listed here. Write for us as a freelancer.

Leave a comment

Your email address will not be published. Required fields are marked *