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.
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.
$ rm ./-my.txt
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.
$ 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.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!
Latest posts by Dan Nanni (see all)
- How to back up a WordPress website to remote cloud storage from the Linux command line - November 24, 2015
- How to access Dropbox from the command line in Linux - November 22, 2015
- How to send email notifications using Gmail SMTP server on Linux - November 9, 2015