1.17 Create hard and soft links

In your Linux file system, a link is a connection between a file name and the actual data on the disk. There are two main types of links that can be created: "hard" links, and "soft" or symbolic links. Hard links are low-level links which the system uses to create elements of the file system itself, such as files and directories.

Hard links

Use the ln command to create additional hard links to an existing file (but not to a directory, even though the system sets up . and .. as hard links).

Now we create some directories and files for test

# mkdir -p hard/link
# touch hard/f1.txt

Now we use ln command to create two hard links, one of them we create in subdirrectory

# ln hard/f1.txt hard/f2.txt
# ln hard/f1.txt hard/link/f3.txt

Put some text into files f1.txt and f2.txt then check content it to f3.txt

# echo 'Hello' > hard/f1.txt
# echo 'world' >> hard/f2.txt
# cat hard/link/f3.txt
Hello
world

Soft links

To create soft link use ln command with -s option. A symbolic link is a special file that points to another file or directory, which is called the target. Once created, a symbolic link can be treated as if it is the target file, even if it is has a different name and is located in another directory. Multiple symbolic links can even be created to the same target file, allowing the target to be accessed by multiple names.

Soft links use file or directory names, which may be relative or absolute. If you are using relative names, you will usually want the current working directory to be the directory where you are creating the link. Otherwise, the link you create will be relative to another point in the file system.

# ln -s ~/hard/f1.txt ~/hard/f4.txt
# cat hard/f4.txt
Hello
world

Lets create soft link on directory

# ln -s ~/hard/link ~/soft
# echo '!' >> soft/f3.txt
# cat hard/f1.txt
Hello
world
!

The symbolic link is a file in its own right, but it does not contain a copy of the target file's data. It is similar to a shortcut in Microsoft Windows: if you delete a symbolic link, the target is unaffected. Also, if the target of a symbolic link is deleted, moved, or renamed, the symbolic link is not updated. When this happens, the symbolic link is called "broken" or "orphaned", and will no longer function as a link.

CentOS 7

No features.

openSUSE Leap 42.3

No features.

Ubuntu 17.04

No features.

Publication/Release Date: Jul 17, 2017

Advertisement