Symlinks (Symbolic links), also called soft links are Linux/UNIX system links referred to the original files, similar to shortcuts in Windows. The symlinks are invalid if the original files are deleted. Hard links on the other hand, are a hard copy of the source files' content, inode number and file permissions, they are independent of the operations on the original.
A hard link cannot cross file system boundaries, therefore you cannot setup a hard link between two directories.
Why Soft links?
You might be running a program that produces a large output and you don't want to overwhelm the file system, soft link allows you to keep the same code but direct the outputs elsewhere.
Create a Symlink
The syntax for setting up a symlink is
ln -s source target
where source is the original file/folder and target is the dummy symlink. If source file path unlikely to change, recommend using absolute path rather than relative path, i.e. both source and target start with either /
(root of the filesystem) or ~
(home directory). This is because ln
command does not check if the source file exists. Let's say you run the above exact command in a directory and then do
file target
you will get a broken symbolic link error even though the command run successfully. To fix the problem, you need to first remove the symlink
rm target
and either make the source file, or setup the symlink using absolute paths.
Remove a Symlink
To remove the relationship, you can run either
unlink symlink
or
rm symlink
Debug Broken Symlink
To see the state of your symlinks, run the following command
ls -l symlink
A broken symlink will be in flashing in red, indicating that the original files are non-existent. The flashing red is a good eye-catcher for spotting problems with symlinks. The first letter of the file permissions (the first column) should be a lower case letter L, l
, indicating it is indeed a symlink. A -
represents a regular file.
If directory default colors are turned on then symlinks will show as light blue but with or without colors on you will see the first character in the out put of ls -l for the symlink name is “l”. This denotes a link. This is different to hard links which are regular files.
Now run
file -L symlink
Look through the output, in my case my symlink was recursively calling itself and I had nested folders within the symlink folder. I deleted the source and reset the symlink.
To see a list of all symlinks in the current directory:
find . -type l
To see a list of broken symlinks in the current directory:
find . -xtype l
To delete all broken symlinks in the current directory:
find . -xtype l -delete
xtype
is a test performed on a dereferenced link and may not be available in all versions of find
.
If previously that symlink is defined for the folder of the file, you have to call command with update parameter
ln -sf source target
Top comments (0)