Symbolic Link Operations

首先了解softlink 解决了hardlink什么问题:

  • Hard links cannot span physical devices or partitions.
  • Hard links cannot reference directories, only files.

Same hard links are spotted by inode value, if a file has mutlipel hard links, then delete all of them in any order would delete the file. You can use stat <file> to check inode and hard links if a file.

A symbolic link, also known as a symlink or a soft link, is a special kind of file (entry) that points to the actual file or directory on a disk (like a shortcut in Windows).

Symbolic links are used all the time to link libraries and often used to link files and folders on mounted NFS (Network File System) shares.

Generally, the ln syntax is similar to the cp or mv syntax:

1
2
cp source destination
ln -s source destination

But if the destination is an directory, soft link will be created inside destination directory.

Create Softlink

For example, create a symbolic link to a file and directory: -s: soft link -n: treat LINK_NAME as a normal file if it is a symbolic link to a directory. 意思是如果LINK_NAME存在并且是一个文件夹softlink,那么还是当做一个普通文件对待,这样就不会再文件夹softlink内部去构造软连接了,一般配合-f使用去replace已经存在的软连接。 -f: remove existing link, otherwise if the link is exist, get error like this:

1
2
3
# you need to remove the link first
# but with -f, no need
ln: failed to create symbolic link ‘xxxx’: File exists

Link path can be absolute or relative, relative is more desirable since the path may be changed. Softlink size is the length of the link path, see in ls -l:

1
2
3
4
# link a file
ln -nfs <path to file> <path to link>
# link a directory
ln -nfs <path to dir> <path to link>

Delete Softlink

There are 2 ways to undo or delete the soft link:

1
2
unlink <link name>
rm [-rf] <link name>

Note that, the rm command just removes the link. It will not delete the origin.

Broken Softlink

Find broken symbolic link:

1
find . -xtype l

If you want to delete in one go:

1
find . -xtype l -delete

A bit of explanation: -xtype l tests for links that are broken (it is the opposite of -type) -delete deletes the files directly, no need for further bothering with xargs or -exec

Ownership of Softlink

How to change ownership from symbolic links? Change permissions for a symbolic link

On most system, softlink ownership does not matter, usually the link permission is 777, for example: lrwxrwxrwx, when using, the softlink origin’s permission will be checked.

How to change the ownership or permission of softlink, chown/chmod -h <link>, if no -h, the chown/chmod will change the ownership of the link origin.

Resources:

SymLink – HowTo: Create a Symbolic Link – Linux How can I find broken symlinks How to delete broken symlinks in one go?

0%