The ln command is used to create a link to a file. Linking enables a file name in one directory (the link) to point to a file in another directory (the target). A link does not contain data of its own, only a reference to the target file. Any changes to the link will reflect in the target file. If you don’t specify the link name, the ln command will create the link in your current working directory.
Syntax
The syntax of the ln command is:
# ln [options] {target name} [link name]
ln Command Options
The ln command has various options. Some of the frequently used options are given in the following table.
Option | Used To |
---|---|
–backup | Back up existing destination files. |
-f | Remove existing destination files. |
-s | Make symbolic links instead of hard links. -i Prompt to remove destination files. |
-v | Print the name of a file before linking. |
Examples of links
The following is an example of creating a hard link using the ln command, where / backup/backup-report is the target of the link, and ~/backup-report is the link itself:
$ ln /backup/backup-report ~/backup-report
The following is an example of the same, but creating a symbolic link instead of a hard link:
$ ln -s /backup/backup-report ~/backup-report
If you enconter the below error while running the ln command:
ln: command not found
you may try installing the below package as per your choice of distribution:
Distribution | Command |
---|---|
OS X | brew install coreutils |
Debian | apt-get install coreutils |
Ubuntu | apt-get install coreutils |
Alpine | apk add coreutils |
Arch Linux | pacman -S coreutils |
Kali Linux | apt-get install coreutils |
CentOS | yum install coreutils |
Fedora | dnf install coreutils |
Raspbian | apt-get install coreutils |
ln Command Examples
1. To create a link of an existing file:
# ln file.txt file.ln
2. To create an soft link for the existing file:
# ln -s file.txt file.ln
3. To make a backup of each destination file:
# ln --backup file.txt file.bk
4. To allow super user to attempt to create hard linked directories:
# ln -d
5. To create the links with removing the existing destination files:
# ln -f # ln --force
6. To prompt whether to remove the destination file:
# ln -i # ln --interactive
7. To make hard links to symbolic link references:
# ln -L # ln --logical
8. To treat the destination symlink directory as file:
# ln -n # ln --no-dereference
9. To make hard links directly to symbolic links:
# ln -P # ln --physical
10. To make symbolic links instead of hard links:
# ln -s
11. To override the usual backup suffix:
# ln -S # ln --suffix=SUFFIX
12. To specify the directory to which the directory should be created:
# ln -t # ln --target-directory=DIRECTORY
13. To treat the link name as normal file:
# ln -T # ln --no-target-directory
14. To print the name of each linked file:
# ln -v # ln --verbose
15. To get the help for ln:
# ln --help
16. To get the version info:
# ln --version