How to safely remove hard-link to home folder

directory-structurehard linkrm

In a folder owned by my user /sites/Website there is a dir named ~.

When I cd to this directory, I am redirected to ~/, my home folder.

At first I thought this was a symbolic link, but doing ls -al shows it to be ordinary. I'm assuming it is a hard link. I ran:

$ rm -r /sites/Website/~

This began to actually delete my home folder and I lost a lot of data. I stopped rm with Ctrlc. How can I get rid of this link safely?

Best Answer

Many shells expand a leading tilde character (~) before a slash at the start of a pathname into the absolute path of your HOME directory. You can prevent this shell expansion by quoting the tilde character or by making sure the tilde doesn't start the pathname:

$ echo "$HOME"
/home/idallen
$ echo ~
/home/idallen
$ echo "~"
~
$ echo \~
~
$ echo ./~
./~

There is nothing special about a tilde character to Unix itself, so you can create a directory named tilde, provided you hide the tilde from expansion by the shell using any of the above methods:

$ mkdir "~"
$ ls -ld '~'
drwxr-xr-x 2 idallen idallen 40 Oct 22 08:45 ~
$ ls -ld \~
drwxr-xr-x 2 idallen idallen 40 Oct 22 08:45 ~
$ ls -ld ./~
drwxr-xr-x 2 idallen idallen 40 Oct 22 08:45 ~
$ ls -ld /tmp/idallen/~
drwxr-xr-x 2 idallen idallen 40 Oct 22 08:45 /tmp/idallen/~

If you don't hide the leading tilde character from the shell, the shell expands it to be your HOME directory. Adding an echo command in front of a command line can show you what the shell does to your command line before it is executed:

$ echo cd ~
cd /home/idallen                 # would go to $HOME directory
$ echo cd ./~
cd ./~                           # would go into directory named ~

You have discovered this need for quoting the tilde, because the commands below would have very different effects, depending on your shell expanding an unquoted leading tilde:

$ echo rm -r ~       
rm -r /home/idallen              # would remove the $HOME directory
$ echo rm -r "~"
rm -r ~                          # would remove the directory named ~
$ echo rm -r ./~
rm -r ./~                        # would remove the directory named ~
$ echo rm -r /tmp/idallen/~
rm -r /tmp/idallen/~             # would remove the directory named ~

Only unquoted tildes at the start of pathnames expand to be your HOME directory.

Related Question