List symlinks in current directory?

16,978

Solution 1

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

Solution 2

This isn't on a Mac, but

find . -maxdepth 1 -type l

works for me.

Solution 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.

Solution 4

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.

Share:
16,978

Related videos on Youtube

cwd
Author by

cwd

Updated on September 18, 2022

Comments

  • cwd
    cwd almost 2 years

    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?

    • Admin
      Admin over 12 years
      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
  • frogstarr78
    frogstarr78 over 12 years
    nice ls solution
  • Peter.O
    Peter.O over 12 years
    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 @
  • Arcege
    Arcege over 12 years
    For the -prune option, you need to use find topdir ! -name topdir -prune; otherwise the starting directory is ignored as well.