4

I accidentally made a directory "~/" under a subdirectory in my home directory. How to safely remove this directory without affecting my home directory. rm -r ~ obviously won't work... Thanks!

2 Answers2

5

When placed in quotes, ~ is never expanded. So:

rm -r '~'

Similarly, tilde expansion is not performed unless the tilde is first character. So, this will also work:

rm -r ./~

Safer approach for removing empty directories

rm -r will remove a directory and all its contents. If you only want to delete a directory if it is empty, then use rmdir instead (Hat tip: Patrick). In this case:

rmdir '~'

Or,

rmdir ./~

Documentation

Tilde Expansion
If a word begins with an unquoted tilde character (~), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the
value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name. [Emphasis added.]

John1024
  • 74,655
0

The command rm -ir -- relativepath/~ will remove it. The -r flag observes whether a directory is empty, only then does it proceed. -i prompts for confirmation before taking action.

user400344
  • 581
  • 4
  • 5
  • Are you sure about the -r flag? Doing rm --help, it says: -r, -R, --recursive remove directories and their contents recursively – Marty Fried Sep 18 '16 at 19:24
  • Apparently I was mistaken. In any case, e.g.: rm -- ./--woops or rm -- --woops work. I distinctly remember a 'directory not empty' error thrown with -r, must be something else. Thanks ;) – user400344 Sep 18 '16 at 19:43