Watch a hard link and a symlink behave differently
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
- Create a file with content:
echo "original content" > target.txt. - Make a hard link and a symbolic link to it:
ln target.txt hard.txtandln -s target.txt soft.txt. - Compare their inode numbers with
ls -li. Note which two share one, and note the link count column. - Delete the original:
rm target.txt. - Read each link. One still produces the content; the other fails. Predict which before you run it.
- Recreate
target.txtwith different content and readsoft.txtagain -- note that the symlink now points at the new file, because it stores a path rather than an identity. - Try to hard-link across filesystems:
ln /etc/hostname /tmp/hnwill fail if/tmpis 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.