How to Symlink a File in Linux

How can I symlink a file in Linux?

To create a new symlink (will fail if symlink exists already):

ln -s /path/to/file /path/to/symlink

To create or update a symlink:

ln -sf /path/to/file /path/to/symlink

Symlink to bash file

ln -s roo.sh /usr/local/bin/roo would create a symlink to a file roo.sh in the same directory (/usr/local/bin/roo --> /usr/local/bin/roo.sh) - you can verify this by using ls -l /usr/local/bin/roo.

To avoid this, use the full path to roo.sh when creating the symlink:

ln -s /path/to/roo.sh /usr/local/bin/roo

Symlink multiple files to an existing folder

Symlinks created with relative paths (i.e. where the source path doesn't start with "/") get resolved relative to the directory the link is in. That means a link to "src/foo.c" in the lang/golang/src/genericc/ directory would try to resolve to lang/golang/src/genericc/src/foo.c which probably doesn't exist.

Solution: either use an absolute path to the source files, like this:

ln -sf /path/to/src/* lang/golang/src/genericc/

or, to get the * wildcard to work right with a correct command, cd to the target directory so the relative paths will work the same way during creation that they will during resolution:

cd lang/golang/src/genericc
ln -sf ../../../../src/* ./

How to find all symlinks to a file?

If you have GNU/BSD find just use -samefile primary.

$ find -L ~/How to Symlink a File in Linux/ -samefile ~/How to Symlink a File in Linux/q/a.txt 
/home/oguz/How to Symlink a File in Linux/q/a.txt
/home/oguz/How to Symlink a File in Linux/w/l2
/home/oguz/How to Symlink a File in Linux/w/l1


Related Topics



Leave a reply



Submit