I am using bash shell in Ubuntu precise.

I am partial to symbolic links in bash even when a hard link would make more sense because they can be more easily identified with an ls. In contrast, for hard links I have to visually compare the inode numbers. This is more cumbersome compared to the output of ls on a soft link which shows the target with "-->" and can have a different colouring scheme applied. Is there a way to have ls visually differentiate hard links from "normal files"? E.g. perhaps by colouring differently files with a reference count of more than 1?

I understand that the question is not framed correctly as conceptually a hard link is just another name for the inode and so indistinguishable from a "normal file" and that there is no concept of a target as in symbolic links but you get my use case.


ls -l output shows the number of hard links to a file system entry between permissions and owner:

$ mkdir foo
$ ls -ld foo
drwxr-xr-x  2 danielbeck  staff  68 15 Aug 18:49 foo

It's 2 by default for empty directories, foo/. and foo. Every subdirectory adds one for its ... Unless you're on OS X and of questionable sanity, that's the only directory hard links you'll get.

Files, of course, only show "real" hard links, so anything but 1 indicates there's a hard link somewhere:

$ touch bar
$ ln bar baz
$ ls -l bar baz
-rw-r--r--  2 danielbeck  staff  0 15 Aug 18:52 bar
-rw-r--r--  2 danielbeck  staff  0 15 Aug 18:52 baz

My (BSD/OS X) ls has no options related to hard links, but you can write your own shell function, like the following, that prints only the hard link count and otherwise is ls -F1 (if ls -l is too cumbersome):

function lss {
    for line in $( ls -d1 $@ )
        do stat -f '%N%T (%l)' "$line"

Output for the two hardlinks and an unrelated file qux:

$ lss bar baz qux
bar (2)
baz (2)
qux (1)

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.