Watch a hard link and a symlink behave differently

short · 20 min · Objective 2.1

Task

Create both kinds of link to the same file, then delete the original and observe what happens to each. This is close to guaranteed on the exam, and it is one of those distinctions that becomes obvious the moment you have watched it rather than read it.

Steps

  1. Create a file with content: echo "original content" > target.txt.
  2. Make a hard link and a symbolic link to it: ln target.txt hard.txt and ln -s target.txt soft.txt.
  3. Compare their inode numbers with ls -li. Note which two share one, and note the link count column.
  4. Delete the original: rm target.txt.
  5. Read each link. One still produces the content; the other fails. Predict which before you run it.
  6. Recreate target.txt with different content and read soft.txt again -- note that the symlink now points at the new file, because it stores a path rather than an identity.
  7. Try to hard-link across filesystems: ln /etc/hostname /tmp/hn will fail if /tmp is a separate mount. Read the error.

Verify

cd ~/lab-links
cat hard.txt                      # still the ORIGINAL content
readlink soft.txt                 # target.txt
stat -c '%h %i %n' hard.txt       # link count and inode
test -e soft.txt && echo "soft resolves" || echo "soft is dangling"

After step 4, cat hard.txt must print the original content and soft.txt must be dangling. If cat soft.txt still works, you deleted the wrong file -- check with ls -l, where a broken symlink is usually shown in red.

Notes

The link count in stat is the number of names the inode has. It starts at 1, becomes 2 when you make the hard link, and returns to 1 when you delete one of them -- and the data is only freed when it reaches 0 and no process holds the file open. That last clause is the deleted-but-open-file case that makes df and du disagree.