ls Command – List Directory Content Ignoring Symlinks

lsrecursivesymlink

I have a directory in which I would like to list all the content (files and sub directories) without showing the symbolic links. I am using GNU utilities on Linux. The ls version is 8.13.

Example:

Full directory listing:

~/test$ ls -Gg
total 12
drwxrwxr-x 2 4096 Jul  9 10:29 dir1
drwxrwxr-x 2 4096 Jul  9 10:29 dir2
drwxrwxr-x 2 4096 Jul  9 10:29 dir3
-rw-rw-r-- 1    0 Jul  9 10:29 file1
-rw-rw-r-- 1    0 Jul  9 10:29 file2
lrwxrwxrwx 1    5 Jul  9 10:29 link1 -> link1
lrwxrwxrwx 1    5 Jul  9 10:30 link2 -> link2

What I would like to get

~/test$ ls -somthing (or bash hack)
total 12
dir1 dir2 dir3 file1 file2

NOTE: My main motivation is to do a recursive grep (GNU grep 2.10) without following symlinks.

Best Answer

For the stated question you can use find:

find . -mindepth 1 ! -type l

will list all files and directories in the current directory or any subdirectories that are not symlinks.

mindepth 1 is just to skip the . current-directory entry. The meat of it is the combination of -type l, which means "is a symbolic link", and !, which means negate the following test. In combination they match every file that is not a symlink. This lists all files and directories recursively, but no symlinks.

If you just want regular files (and not directories):

find . -type f

To include only the direct children of this directory, and not all others recursively:

find . -mindepth 1 -maxdepth 1

You can combine those (and other) tests together to get the list of files you want.

To execute a particular grep on every file matching the tests you're using, use -exec:

find . -type f -exec grep -H 'some pattern' '{}' +

The '{}' will be replaced with the files. The + is necessary to tell find your command is done. The option -H forces grep to display a file name even if it happens to run with a single matching file.