How to Fix Linux Broken Symlink Error
In this tutorial, you'll learn about How to Fix Linux Broken Symlink Error. We cover key concepts, practical examples, and best practices.
You try to access a symlink and get No such file or directory — the file the symlink points to has been moved or deleted, leaving a dangling reference.
The Problem
ls -la link.txt
lrwxrwxrwx 1 user user 24 Jun 24 10:00 link.txt -> /path/to/nonexistent/file.txt
cat link.txt
cat: link.txt: No such file or directory
Step-by-Step Fix
Step 1: Find broken symlinks
find . -type l ! -exec test -e {} \; -print
Or more efficiently:
find . -xtype l
Step 2: Remove broken symlinks
# Remove all broken symlinks in current directory
find . -xtype l -delete
# Remove with confirmation
find . -xtype l -ok rm {} \;
Step 3: Recreate the symlink with the correct target
# WRONG — points to moved/deleted file
ln -s /old/path/file.txt link.txt
# RIGHT — point to the new location
rm link.txt
ln -s /new/path/file.txt link.txt
Step 4: Verify the symlink
ls -la link.txt
Expected:
lrwxrwxrwx 1 user user 24 Jun 24 10:01 link.txt -> /new/path/file.txt
cat link.txt
file contents here
Step 5: Use realpath to resolve symlinks
realpath link.txt
If the target does not exist, you get:
realpath: link.txt: No such file or directory
Step 6: Fix relative symlinks
# WRONG — target relative to current directory, not symlink location
ln -s ~/project/data/file.txt symlink_in_other_dir
# RIGHT — use relative path from symlink's directory
rm symlink_in_other_dir
ln -s ../data/file.txt symlink_in_other_dir
Prevention Tips
- Use
ln -srfor relative symlinks - Check symlink targets after moving files
- Use
find . -xtype lperiodically to audit - Update symlinks when restructuring directories
- Prefer hard links for files that must stay in sync
Common Mistakes with symlink broken
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world LINUX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro