How to delete files starting with dash/hyphen

Deleting files starting with dash or hyphen can be little tricky as dash is interpreted as option prefix on Mac and Linux. Here is what happens when we try to delete file starting with dash on Ubuntu Linux:

$ echo "foo" > -file1.txt
$ ls -l
total 4
-rw-rw-r-- 1 user1 uer1 4 Oct  3 06:26 -file1
$ rm -file1.txt
rm: invalid option -- 'l'
Try 'rm ./-file1.txt' to remove the file ‘-file1.txt’.
Try 'rm --help' for more information.

The trick is to use double-dash -- to specify end of command options. To delete -file1.txt we can run the following command:

$ rm -- -file1.txt

In case you want to rename the file, you can run mv as shown below:

$ mv -- -file1.txt file1.txt
$ ls -l 
total 4
-rw-rw-r-- 1 user1 user1 4 Oct  3 06:32 file1.txt
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments