62

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
done

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
done

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'
71

Just combine the two tests with &&:

if [[ -L "$file" && -d "$file" ]]
then
    echo "$file is a symlink to a directory"
fi
  • 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
7

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

1

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";
    fi; 
done
  • 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.