How to create a file with a "#" character in the name in Unix?

Solution 1:

The two canonical ways to create/delete files with "funny characters" are

  1. Quoting, like alex showed. You may use single or double quotes, depending on your expansion needs. A backslash can be used to escape a single funny charater. This works as long as the file name does not look like an option (starts with a dash).
  2. If the file looks like an option, prepend a path: rm ./- "./-rf ."

Modern versions of Unix utilities often support the double dash to indicate the end of options. On such systems, rm -- - removes a file named -.

Note that you cannot create or remove files with a slash or ASCII NUL in their name. If you have such a file (I've seen them), something in your file system has gone terribly wrong.

In your particular case with the hash #, the problem stems from the shell interpreting a word starting with # as starting a shell comment. A good shell lets you disable this shell feature, called interactive comments:

  • zsh: unsetopt interactivecomments
  • bash: shopt -u interactive_comments

With these you can simply touch #; rm # without hassle.

Solution 2:

To make...

touch "#file"

To delete...

rm "#file"