How to remove a folder that starts with “$”?

6,882

Solution 1

$, space, ' and [ are special characters in most shells. To remove their special meaning, you have to use the quoting mechanisms of the shell.

The quoting syntax varies very much with the shell.

In all shells that I know, you can use single quotes to quote all characters but single quote, backslash and newline (in Bourne-like shells, it does quote the last two as well, except in backticks for \ in some).

rm -r '$pattern'

Should work in most common shells.

rm -r \$pattern

Would work (except inside backticks for Bourne-like ones) in all shells but those of the rc family.

Same for:

rm "\$option[value='2016']"

In rc-like shells, you'd use:

rm '$option[value=''2016'']'

Solution 2

If directory is empty:

rmdir \$pattern

Otherwise:

rm -r \$pattern

(It will delete recursevely any file that the folder contains)

Solution 3

When you need to operate on a file which contains special characters, an option is to use the bash autocomplete feature: start typing your command (in this case rmdir) and then hit Tab several times. This will cycle around all the files/directory in the current directory, automatically escaping all special characters.

This also works well if you're operating on very long filenames.

Share:
6,882

Related videos on Youtube

Gilles 'SO- stop being evil'
Author by

Gilles 'SO- stop being evil'

Updated on September 18, 2022

Comments

  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 1 year

    I created a directory named "$pattern" and now when ever i try to remove it, it says

    pattern: Undefined variable.

    I have tried:

    $ rm -r $pattern
    $ rm -rf $pattern
    $ rm "$ option[value='2016']"
    
    • Admin
      Admin over 7 years
      In what shell, Vipanchi?
  • kba
    kba over 7 years
    You can also singlequote to avoid escaping: rm '$pattern'
  • Toby Speight
    Toby Speight over 7 years
    "This will cycle around ..." - not by default; you need to bind TAB to menu-complete instead of complete.