Let’s say when I do ls -li inside a directory, I get this:
12353538 -rw-r--r-- 6 me me 1650 2013-01-10 16:33 fun.txt
As the output shows, the file fun.txt has 6 hard links; and the inode number is 12353538.
How do I find all the hard links for the file i.e. files with the same inode number?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
find /mount/point -mount -samefile /mount/point/your/file
Method 2
If you already have the inode number you can use find’s -inum option:
find /mount/point -xdev -inum 12353538
(some find implementations also support -mount as an equivalent of -xdev though only -xdev is standard).
Method 3
ffind from The Sleuth Kit can find all the file names for an inode, including deleted file names.
For example:
sudo ffind -a /dev/sda3 $(stat --format=%i ~/just_a_test)
yields
* /home/me/empty_1 * /home/me/hard_link_to_empty1 /home/me/just_a_test /home/me/hard_link_to_just_a_test
The entries with a preceding star are previous file names that don’t exist anymore (because the file was renamed or deleted).
I use $(stat --format=%i ~/just_a_test) to get the inode of the file.
To get the partition of the file name programmatically (/dev/sda3 in the previous example), you can use df:
file=~/just_a_test; sudo ffind -a $(df -P "$file" | awk 'END{print $1}') $(stat --format=%i "$file")
Method 4
With thanks to the previous answers.
Note that the stat binary can not only provide one with the inode, but its corresponding device’s mount point too. The snippet below uses this to solve the ‘usual’ use case:
fn_hardlinks() {
declare target; target="$1" && shift
[ ! -e "$target" ] &&
{ echo "[error] invalid target: '$target'" 1>&2; exit 1; }
stat '/' 2>/dev/null 1>&2 ||
{ echo "[error] no functioning 'stat' binary found'" 1>&2; exit 1; }
declare mount; mount="$(stat -c '%m' "$target")"
declare inode; inode="$(stat -c '%i' "$target")"
[ "x${mount[-1]}" != "x/" ] && mount+="/"
find "$mount" -xdev -inum "$inode" 2>/dev/null
}
alias hardlinks=fn_hardlinks
and running:
> hardlinks ./resources/sphinx/gitinfo.py /home/user/build/z-documentation/resources/sphinx/gitinfo.py /home/user/build/sphinx-gitinfo/git/sphinx-gitinfo/gitinfo.py
PS: watch out for exit vs return depending on how you use this!
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0