ln - macOS


Overview

ln is a versatile macOS command used to create symbolic or hard links between files and directories. Symbolic links reference the original file, while hard links create duplicate entries that point to the same physical data. It facilitates file organization, allows multiple aliases for the same data, and provides the ability to share data efficiently.

Syntax

ln [-s] [-T follow] [-v] [-F] [-n force] target link_name

Required arguments:

  • target: The existing file or directory to link to.
  • link_name: The desired name of the link to be created.

Options/Flags

  • -s: Creates a symbolic link (default).
  • -T follow: Resolves symbolic links when creating hard links.
  • -v: Enables verbose output, displaying the created links.
  • -F: Skips the creation of hard links if the target is a directory or a dangling symbolic link.
  • -n force: Overwrites existing files without confirmation.

Examples

Simple symbolic link:

ln -s /Applications/Safari.app ~/Desktop/Safari

Hard link to a file:

ln /tmp/test.txt /tmp/testlink.txt

Hard link to a directory (resolving symbolic links):

ln -T follow /tmp/dir /tmp/otherdir

Create links with specific names:

ln -s /Applications/Safari.app SafariLink
ln /tmp/test.txt testLinkName

Common Issues

  • Dangling symbolic links: Occurs when the target file no longer exists. Use -F or remove the broken link with unlink.
  • Permission issues: Ensure you have write permissions to create links.
  • Circular links: Avoid creating links that point to each other, as it can cause infinite loops.

Integration

  • locate: Use locate to find the target file’s location before creating links.
  • find: Combine with find to create links for multiple files in a directory.
  • rsync: Use ln to preserve hard links during file transfer.
  • unlink: Removes links.
  • cp: Copies files and directories.
  • mv: Moves or renames files and directories.
  • stat: Displays file and link information.