How to create a file with a “#” character in the name in Unix

filenamesunix

I've tried many commands already for creating a file and deleting a file with a # character, but it does not work. Can anyone tell me the command to create and then delete a file that begins with #?

Best Answer

  • 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.

  • Related Question