Thursday, January 22, 2015

How to manage files whose name starting with hyphen (-), or double hyphen (--)

There are a few ways you can manage these kind of files, the normal way won't work, since this filename will be treated as options for almost all commands. Please see below on the method to manage these files:

Let's say the file name is -p, and you are trying to delete it,  the usual error is, since the -p is being treated as the flag for command rm, rather than a file name:

$ rm -p
rm: invalid option -- 'p'
Try 'rm ./-p' to remove the file ‘-p’.
Try 'rm --help' for more information.


So, the correct way to manage this file is:

To list:

$ ls ./-p
$ ls -- -p
$ find . -maxdepth 1 -iname "-p"


To delete:
$ rm -- -p
$ rm ./-p
$ find . -maxdepth 1 -iname "-p" -delete


To create:
$ touch ./-p


Basically, the ./ can be used with any command, while the " -- " have been tested working with ls and rm.

Hope this is helpful, thanks to stackexchange for this useful tips.

No comments: