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

Run this twice -- once straight after step 4, and again after step 6 -- because the right answer for soft.txt changes between them, and that change is the lesson:

cd ~/lab-links
cat hard.txt                      # still the ORIGINAL content, both times
readlink soft.txt                 # target.txt, both times -- it stores a path
stat -c '%h %i %n' hard.txt       # link count 1 after step 4: one name left
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 at that point, you deleted the wrong file -- check with ls -l, where a broken symlink is usually shown in red. After step 6 the same last line prints "soft resolves", and cat soft.txt prints the NEW content while cat hard.txt still prints the old: the hard link kept the original inode, the symlink followed the name.

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.

This is an independent study companion for CompTIA Linux+ and is not produced by or endorsed by CompTIA.