To create a symbolic link (symlink) in Linux, use the ln
command with the -s
(symbolic) option. A symlink acts as a shortcut to another file or directory.
Basic Syntax
ln -s <source_path> <symlink_name>
Examples
1. Create a Symlink to a File
# Create a symlink "shortcut.txt" pointing to "original.txt"
ln -s /path/to/original.txt shortcut.txt
2. Create a Symlink to a Directory
# Create a symlink "my_folder" pointing to "/var/www/html"
ln -s /var/www/html my_folder
3. Overwrite an Existing Symlink
Use -f
(force) to replace an existing symlink:
ln -sf /new/target existing_symlink
4. Use Relative Paths
Create a symlink using a relative path (useful for portability):
# From the current directory, link to "../data/config.json"
ln -s ../data/config.json config_link
Verify Symlinks
- Check symlink details with
ls -l
:
ls -l shortcut.txt
Output example:
lrwxrwxrwx 1 user group 15 Jun 1 10:00 shortcut.txt -> original.txt
- Use
readlink
to see the target:
readlink shortcut.txt
Key Notes
- Permissions: Symlinks inherit the target’s permissions.
- Dangling Links: If the source file/directory is deleted, the symlink becomes “broken” (dangling).
- Delete a Symlink:
unlink symlink_name # Safely remove the symlink
# OR
rm symlink_name # Standard delete
Common Errors & Fixes
Error | Solution |
---|---|
ln: failed to create symbolic link: File exists | Use -f to overwrite. |
ln: target 'symlink' is not a directory | Specify a valid source path. |
Symbolic Link vs. Hard Link
Feature | Symbolic Link (ln -s ) | Hard Link (ln ) |
---|---|---|
Cross-Filesystem | Yes | No |
Link to Directories | Yes | No |
Target Deletion | Link breaks | Link remains valid |
Use symlinks for flexible file/directory references!