Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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 {
    OLDIFS="$IFS"
    IFS=$'\n'
    for line in $( ls -d1 $@ )
        do stat -f '%N%T (%l)' "$line"
    done
    IFS="$OLDIFS"
}

Output for the two hardlinks and an unrelated file qux:

$ lss bar baz qux
bar (2)
baz (2)
qux (1)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.