Creating links with ln
- Version
- unversioned
- Review
- Draft
Summary#
ln creates another name for a file. A hard link refers to the same file data, while a symbolic link stores a path that is resolved when the link is used.
Syntax#
ln target hard_link
ln -s target symbolic_link
ln -sfn new_target symbolic_link
readlink symbolic_link
The target comes first and the new link name second. A symbolic link can point to a path that does not exist yet.
Example#
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
mkdir -p releases/v1 releases/v2
echo 'version 1' > releases/v1/VERSION
echo 'version 2' > releases/v2/VERSION
ln -s releases/v1 current
cat current/VERSION
ln -sfn releases/v2 current
cat current/VERSION
readlink current
echo '-- remove the original name'
echo 'data' > original.txt
ln original.txt hard.txt
ln -s original.txt soft.txt
rm original.txt
cat hard.txt
if [ -e soft.txt ]; then echo 'soft link resolves'; else echo 'soft link is dangling'; fi
)
Expected output#
version 1
version 2
releases/v2
-- remove the original name
data
soft link is dangling
Common mistakes#
A relative symbolic link target is resolved from the directory that contains the link, not from your current directory. When replacing a link that points to a directory, include -n; without it, ln -sf creates the new link inside that directory. Check the destination before using -f, which can also replace a regular file. GNU ln -T treats the destination as the exact link name even if it is a directory.
Version applicability#
This entry describes GNU coreutils ln. Option behavior can differ in other implementations.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0