Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find symlinks to certain directory or one of its subdirs

Is there an easy way to show whether there are any symlinks in a specified path pointing to a certain directory or one of its children?

like image 512
Pekka Avatar asked Dec 10 '09 20:12

Pekka


People also ask

How do I find a symlink in a directory?

Use the ls -l command to check whether a given file is a symbolic link, and to find the file or directory that symbolic link point to. The first character “l”, indicates that the file is a symlink. The “->” symbol shows the file the symlink points to.

How do I find only directories and soft links in a particular directory?

The first way is by using the ls command in UNIX which displays files, directories, and links in any directory and the other way is by using UNIX find command which has the ability to search any kind of file e.g. file, directory, or link.

Can a symbolic link point to a directory?

Symlink, also known as a symbolic link in Linux, creates a link to a file or a directory for easier access. To put it in another way, symlinks are links that points to another file or folder in your system, quite similar to the shortcuts in Windows.


2 Answers

A simple and fast approach, assuming that you have the target as absolute path (readlink(1) may help with that matter):

find $PATH -type l -xtype d -lname "$DIR*"

This finds all symlinks (-type l) below $PATH which link to a directory (-xtype d) with a name starting with $DIR.


Another approach, which is O(n*m) and therefore may take ages and two days:

find $DIR -type d | xargs -n1 find $PATH -lname

The first find lists $DIR and all its subdirectories which are then passed (xargs), one at a time (-n1), to a second find which looks for all symlinks originating below $PATH.


To sum things up: find(1) is your friend.

like image 175
earl Avatar answered Nov 15 '22 11:11

earl


Following up on the answer given by earl:

-xtype does not work on Mac OSX, but can be safely omitted:

find $PATH -type l -lname "$DIR*"

Example:

find ~/ -type l -lname "~/my/sub/folder/*"
like image 26
sqren Avatar answered Nov 15 '22 13:11

sqren