How to ls using the long format (-l) while still following directory symlinks?

I’ve noticed that ls -l doesn’t only change the formatting of the output, but also how directory symlinks are handled:

> ls /rmn  logs ...

> ls -l /rmn
lrwxrwxrwx 1 root root 18 Feb 11  2011 /rmn -> /root/maintenance/

I’d like to get a detailed listing of what’s in /rmn, not information about the /rmn symlink.

One work-around I can think of is to create a shell function that does something like this:

cd /rmn
ls -l
cd -

But that seems too hacky, especially since it messes up the next use of cd -. Is there a better way?

(I’m on CentOS 2.6.9)

Asked By: RomanSt


See if your ls has the options:

 -H, --dereference-command-line
     follow symbolic links listed on the command line 
     follow each command line symbolic link that points to a directory

If those don’t help, you can make your macro work without messing up cd - by doing:

(cd /rmn ; ls -l)

which runs in a subshell.

Answered By: pjc50
ls -l /rmn/

would do it or

ls -l /rmn/.

However, the behavior should not be different with and without -l. Have you got an alias for ls?

Answered By: Stéphane Chazelas

I don’t quite get why the thinking about this simple problem has to be so complex – but perhaps I just got the question the wrong way. Anyways: when I needed a similar functionality, I used:

ls -lL

That did the trick in my case.
From the ls man page:

-L, --dereference
     when showing file information for a symbolic link, 
     show  information  for  the file the link references
     rather than for the link itself

For instance, I’ve made me a /media/stick shortcut to access the data on my USB stick. ls -l /media/stick will show the actual link, while ls -lL /media/stick will show the contents on the USB stick.

After some deeper research about the difference between the inner workings of -H and -L, I finally came across an excellent article about this matter on Shallow Thoughts blog (even featuring some neat shell script tricks for your pleasure!)

This points out the subtle differences between the two options (way better than the original manual does!) as follows:

  • -H — only dereference those links explicitly mentioned on the command line
  • -L — dereference links even if they are not mentioned on the command line

(When these two are used with simple everyday tasks, there ought to be no difference in the output in general.)

Besides: Should you prefer to remember the long form (--option), it’s most probably less cumbersome to memorize --dereference than the excessively long monster of --dereference-command-line-symlink-to-dir.

Answered By: syntaxerror
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.