DEV Community

Cover image for Creating Symlinks in Linux
Dev Diaries
Dev Diaries

Posted on

Creating Symlinks in Linux

A SymLink in Linux is a special kind of file that points to an actual file or directory, basically a shortcut, but a little different as a symlink is an actual pointer to the source file or directory. Symlinks can be very useful for example if you want to version files you can bump a version app_v2 but just have a symlink that refers app_latest that just references the latest version.

ln -s /path/to/source /path/to/symlink

Some useful SymLink options are:

-f   If the target file already exists, then unlink it and force the link

-n   Useful with the -f option, replace the symlink that might point to a directory

One important thing to remember is that you must use the full path when creating symlinks and not the relative paths. For example if you have this as your filesystem

> ls
image.png

We want to create another directory (folder) called pics that contains a symlink
to image.png within it.

> mkdir pics

> ls
image.png
pics

If we tried to symlink just using relative paths the symlink would be broken:

> ln -s image.png ./pics/image.png

Instead, we should use the full path and in our case we can use the $PWD value which expands to our present working directory:

> ln -s $PWD/image.png $PWD/pics/image.png

Another option is to actually change directories into the pics directory and create the symlink from there:

> cd pics
> ln -s ../image.png image.png

Original Post on Dev Diaries
Instagram Post On Dev Diaries

Oldest comments (4)

Collapse
 
taylorsilva profile image
Taylor Silva • Edited

Check out GNU stow! It's been a good tool for me for managing symlinks

Collapse
 
devdiaries profile image
Dev Diaries

Thanks! Will check it out

Collapse
 
briedis profile image
Mārtiņš Briedis

One of the most common uses is when configuring nginx. Site config files are in sites-available, and you create symlinks to sites-enabled, so you can always remove sites by deleting them from sites-enabled directory without losing the original configuration files.

Collapse
 
devdiaries profile image
Dev Diaries

Indeed, thanks for adding!