Removing or Renaming Files Named with Special Characters
Problem
You need to remove or rename a file that was created with a special character that causes rm or mv to behave in unexpected ways. The canonical example of this is any file starting with a dash, such as -f or --help, which will cause any command you try to use to interpret the filename as an argument.
Solution
If the file begins with a dash, use -- to signal the end of arguments to the command, or use a full (/tmp/-f) or relative (./-f) path. If the file contains other special characters that are interpreted by the shell, such as a space or asterisk, use shell quoting. If you use filename completion (the Tab key by default), it will automatically quote special characters for you. You can also use single-quotes around the troublesome name.
$ ls
--help this is a *crazy* file name!
$ mv --help help
mv: unknown option -- -
usage: mv [-fiv] source target
mv [-fiv] source ... directory
$ mv -- --help my_help
$ mv this\ is\ a\ \*crazy\*\ file\ name\! this_is_a_better_name
$ ls
my_help this_is_a_better_nameDiscussion
To understand what is actually being executed after shell expansion, preface your command with echo:
$ rm *
rm: unknown option -- -
usage: rm [-f|-i] [-dPRrvW] file ...$ echo rm *
rm --help this is a *crazy* file name!Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access