5

I was working on a shell script and I accidentally created a file with the variable as its name. Now I have $file in my ls output, and cannot remove it. What can I do?

6 Answers 6

14

You can escape the $ with \:

rm \$file
2
  • Maybe add a comment about escaping special characters?
    – Keith
    Jun 2, 2011 at 3:34
  • 4
    It wouldn't hurt to use the -i switch (interactive, so you are prompted before the final removal) in this case...
    – jasonwryan
    Jun 2, 2011 at 3:40
6

You can also do

rm '$file'

Stuff in single quotes is taken as literal always,so globs and variables don't get expanded.

6

Basically, if you want to do things literal with these weird characters, you need to escape it. In a shell there are several ways to do that. The first one is to prepend a '\' to every character you want to escape. So you can do rm \$file. Another way is to quote them with single quotes, for example, rm '$file' or rm '$'file. Some people also consider double quotes as a mean to "escape", but it only escapes white spaces. For example if you have a file named a file, you can do

rm a\ file

or

rm 'a file'

or

rm "a file"
1
  • 1
    "..." doesn't only escape white space, it escapes all but backslash, $, ` and " itself (and possibly ! if history expansion is not enabled. Note that backslash doesn't escape the newline character, it removes it instead (serves as line continuation) Feb 19, 2020 at 20:30
4

If you ever accidentally create a file named -rf, you can use rm -- -rf to delete it.

3
  • This seems scary to try to test. :-) Jun 2, 2011 at 9:49
  • @Peter Grill: This is exactly why the -- option was created; to remove files that would otherwise be taken as options. Alternatively, you could test it with a brand-new directory named '-rf': rm -- -rf should give you an error about being a directory.
    – Kevin M
    Jun 2, 2011 at 15:59
  • Hmm... what about files named --...? Ah, no problem: rm -- -- Oct 9, 2014 at 3:41
0

Any graphical file manager should be able to handle this through the context menu, because it doesn't try to interpret anything.

1
  • 1
    Or, equivalently, you could hire a sysadmin to do it, right? ;)
    – Wildcard
    Apr 4, 2016 at 18:58
0

Some ways to get rid of files with weird names are to use globbing (i.e., rm ?file if the first character is something strange, but that would also nuke Xfile, need to be careful not to match too much, check with echo beforehand) and/or use the interactive flag: rm -i *file will ask for all stuff called somethingfile if you want to delete it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.