Delete a File With Invalid or Bad Characters in File Name on FreeBSD

There once was a time when I did the following inside my home directory:

$ wget "some-url" -O "output-file.mp4"

I clearly remember copying the output file name from a web page. Unfortunately, the copied text has a new line at the beginning of it and I didn’t notice that. That’s because the newline or carriage return characters are control characters and have no visual representation. Anyway, when I listed files inside my home directory I noticed a strange file name on my list:

$ ls
?output-file.mp4

I tried the following to remove the file without any success:

$ rm "?output-file.mp4"
rm: ?output-file.mp4: No such file or directory

$ rm \?output-file.mp4
rm: ?output-file.mp4: No such file or directory

$ rm ./?output-file.mp4
rm: ./?output-file.mp4: No such file or directory

$ rm *.mp4
rm: *.mp4: No such file or directory

When I tried auto-completion by pressing Tab key a few times on csh it showed the file name as:

output-file.mp4

On the other hand bash showed the following name:

    ^Joutput-file.mp4

I tried the above rm command with ^J instead of ? with no luck.

In the next step, I tried:

$ man rm

Then I came across -i flag inside rm man page:

-i Request confirmation before attempting to remove each file, regardless of the file’s permissions, or whether or not the stan- dard input device is a terminal. The -i option overrides any previous -f options.

FreeBSD Man Pages rm

So, I gave rm -i a go after changing to my home directory:

$ cd ~
$ rm -i *
remove
output-file.mp4 ? y
remove some-other-file ? ^C

As it can be seen in the output, rm now considers the file and even prints the newline character in the output. So I entered y and it deleted the file with bad name. For, the other files on the list I simply pressed Ctrl+C to exit the list completely (Note: if Ctrl+C won’t work for you, try Ctrl+Z or Ctrl+D).

I also found an interesting flag through my journey inside rm man page which may come handy one day:

The rm command uses getopt(3) to parse its arguments, which allows to accept the --' option which will cause it to stop processing flag options at that point. This will allow the removal of file names that begin with a dash (-’). For example:

rm – -filename

The same behavior can be obtained by using an absolute or relative path reference. For example:

rm /home/user/-filename rm ./-filename

FreeBSD Man Pages rm