I can check, if a file exists and is a symbolic link with -L

for file in *; do
    if [[ -L "$file" ]]; then echo "$file is a symlink"; else echo "$file is not a symlink"; fi

and if it is a directory with -d:

for file in *; do
    if [[ -d "$file" ]]; then echo "$file is a directory"; else echo "$file is a regular file"; fi

But how can I test for only links to directories?

I simulated all cases in a test folder:

/tmp/test# ls
a  b  c/  d@  e@  f@

/tmp/test# file *
a: ASCII text
b: ASCII text
c: directory
d: symbolic link to `c'
e: symbolic link to `a'
f: broken symbolic link to `nofile'

Just combine the two tests with &&:

if [[ -L "$file" && -d "$file" ]]
    echo "$file is a symlink to a directory"
  • 1
    If you want to check hidden files and directories too preceed this before: shopt -s dotglob – rubo77 May 29 '14 at 16:04
  • 2
    Isn't [ -L "$file" ] && [ -d "$file" ] better? Something with portability between shells iirc. – Lennart Rolland May 29 '15 at 22:29
  • 3
    @Lennart OP's example code uses [[, and I took that as the logical starting point. A discussion of the merits of [ vs [[ is out of scope for this answer (but available here). – user27282 May 30 '15 at 1:56

Here is a single command which will recursively list symlinks whose target is a directory (starting in the current directory):

find . -type l -xtype d

Reference: http://www.commandlinefu.com/commands/view/6105/find-all-symlinks-that-link-to-directories


A solution with find and using a function:

dosomething () {
    echo "doing something with $1"; 
find -L -path './*' -prune -type d| while read file; do 
    if [[ -L "$file" && -d "$file" ]];
        then dosomething "$file";
  • Using find and a while read for that is kinda overkill... – Camilo Martin Aug 20 '14 at 14:20
  • 1
    Find is really useful if you search only for certain files – rubo77 Aug 21 '14 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.