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

5

1

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 #?

tonberry

Posted 2011-04-10T04:58:57.437

Reputation:

2Note: You should say "a filename that begins with the symbol #", not a file, otherwise some people (like me) will think you mean the first line of the file should start with a #. – Robin Green – 2011-04-10T13:45:13.753

Answers

11

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.

Jens

Posted 2011-04-10T04:58:57.437

Reputation: 507

5

To make...

touch "#file"

To delete...

rm "#file"

alex

Posted 2011-04-10T04:58:57.437

Reputation: 3 604

2Also touch \#file or rm \#file – Kevin Lacquement – 2011-04-10T05:48:09.727

2or touch '#file' and rm '#file' – Philipp – 2011-04-10T10:04:16.067

thanks for your helping. but if what to create file and delete file using "-" symbol why cannot already? – None – 2011-04-10T12:58:56.510

Because - introduces options. rm - looks to rm like you forgot an option and thus complains. – Jens – 2011-04-16T08:37:10.280