9

This question talks about finding directories in a current diretory. The solution is basically:

ls -d */

That's great but how can I easily list symlinks? Do I have to use something like

find . -xtype l -d 1
(intended to find symlinks max depth 1 - doesn't work)

Or is there an easier way? Can ls be used for this?

cwd
  • 44,479
  • 71
  • 146
  • 167
  • On my Ubuntu system, a quick look at its `man find` shows that `-d` is a synonym for `-depth` (for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD.), ie. it is not the same as `-maxdepth` . . . `-depth` *Process each directory's contents before the directory itself* – Peter.O Oct 04 '11 at 04:04

4 Answers4

9

In zsh (add N inside the parentheses to include symlinks whose name begins with a .):

echo *(@)

With most find implementations:

find -maxdepth 1 -type l

POSIX-compliant:

find . -type d \! -name . -prune -o -type l -print

Or with a shell loop:

for x in * .*; do
  if [ -h "$x" ]; then echo "$x"; done
done
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • 1
    For the `-prune` option, you need to use `find topdir ! -name topdir -prune`; otherwise the starting directory is ignored as well. – Arcege Oct 04 '11 at 10:55
7

This isn't on a Mac, but

find . -maxdepth 1 -type l

works for me.

frogstarr78
  • 994
  • 1
  • 6
  • 13
3

You should be using -type and not -xtype:

   -xtype c
          The same as -type unless the file is a symbolic link.  For  sym‐
          bolic  links:  if the -H or -P option was specified, true if the
          file is a link to a file of type c; if the -L  option  has  been
          given,  true  if  c is `l'.  In other words, for symbolic links,
          -xtype checks the type of the file that -type does not check.

The default is -P, so the -xtype option will try to determine the resultant file, not the symlink itself. Actually, I get some positive results, which seems like a bug. The -P -xtype l should return true (on a symlink) iff the resultant is itself a symbolic link.

Can also use: ls -FA | sed -ne 's/@//p' which will display only the symlinks.

Arcege
  • 22,287
  • 5
  • 56
  • 64
  • nice ls solution – frogstarr78 Oct 04 '11 at 03:56
  • 2
    `sed -ne 's/@//p'` (and even `sed -ne 's/@$//p'`) is not a secure test, as the first version will give a false positive when `@` occurs anywhere in the *ls* output, and the second will return a false postive when a filename actually ends in `@` – Peter.O Oct 04 '11 at 04:39
1

To find out only the files that are symlinks inside the current directory:

find . -type l -printf '%p -> %l\n'

This will recursively list all the symlink files. Also, it shows the actual files it points to.

Stéphane Gimenez
  • 28,527
  • 3
  • 76
  • 87