Как найти жесткие ссылки в линукс

If the given file is called /path/to/file and you want to find all hard links to it that exist under the current directory, then use:

find . -samefile /path/to/file 

The above was tested on GNU find. Although -samefile is not POSIX, it is also supported by Mac OSX find and FreeBSD find.

Documentation

From GNU man find:

-samefile name
       File refers to the same inode as name. When -L is in effect, this can include symbolic links.

Differences between find and ls

ls -l lists the number of hard links to a file or directory. For directories, this number is larger than the number of results shown by find . -samefile. The reason for this is explained in the GNU find manual:

A directory normally has at least two hard links: the entry named in
its parent directory, and the . entry inside of the directory. If a
directory has subdirectories, each of those also has a hard link
called .. to its parent directory.

The . and .. directory entries are not normally searched unless they
are mentioned on the find command line.

In sum, ls -l counts the . and .. directories as separate hard links but find . -samefile does not.

Как найти все жесткие ссылки (hard link) в каталоге в LinuxУ меня есть файл с именем /etc/passwd i , и я хотел бы найти все жесткие ссылки на этот файл в каталоге. Как узнать все остальные жесткие ссылки в каталоге /etc/passwd in/backups/ ? Как найти все жесткие ссылки на данный файл с помощью командной строки Linux или Unix?

Вы можете использовать команду find  в Linux, Apple MacOS, FreeBSD и других операционных системах, чтобы узнать все жесткие ссылки.

Как найти все жесткие ссылки на предоставленный файл

Жесткая ссылка — это не что иное, как конкретное местоположение физических данных. Вы даете разные имена, относящиеся к одному и тому же файлу. Файл относится к тому же inode, что и имя. Жесткие ссылки на файл foo можно создать следующим образом:

$ ln foo bar
$ ln foo dir2/foobar

В приведенном выше примере bar и foobar являются другими именами файла foo. Lля поиска всех жестких ссылок для файла foo в текущем каталоге cинтаксис будет выглядеть следующим образом:

find /dir/to/search/ -samefile /path/to/file/name
## To find out all hard links to foo, use this command:
find / -samefile foo
find / -xdev -samefile foo

Примеры

Если есть файл с именем /etc/passwd  и вам нужно получить все жесткие ссылки на него, которые существуют в каталоге /backups/ , запустите:

$ find /backups/ -samefile /etc/passwd

Примеры возможных выводов данных:

/backups/hourly.0/etc/passwd
/backups/hourly.4/etc/passwd
/backups/hourly.3/etc/passwd
/backups/daily.0/etc/passwd
/backups/hourly.1/etc/passwd
/backups/hourly.2/etc/passwd

Если вы не хотите спускать каталоги на другие файловые системы, смонтированные однажды, попробуйте ввести:

$ find /backups/ -xdev -samefile /etc/passwd

Найдите и удаляйте все жесткие ссылки на файл с именем foo в /tmp/ директории

Введите следующую команду:

$ find /tmp/ -xdev -samefile foo -print0 | xargs -I {} -0 rm -v {}

Примеры возможных выводов данных:

removed '/tmp/dir2/foobar'
removed '/tmp/foo'
removed '/tmp/bar'

Справка, параметр -samefile не поддерживается моей командой find

Найдите номер файлов inode, для этого введите:

$ ls -li fileNameHere
$ ls -li /tmp/demo.txt

Примеры возможных выводов данных:

4065089 -rw-r--r-- 3 vivek vivek 8 Feb 26 02:19 /tmp/demo.txt

Первый столбец вышеприведенного вывода отображает индекс inode # 4065089 . Теперь альтернативный синтаксис выглядит следующим образом для поиска всех жестких ссылок (hard link) для файла с именем /tmp/demo.txt , используя inode # 4065089 :

$ find /tmp/ -inum 4065089
$ find /tmp/ -xdev -inum 4065089

Примеры возможных выводов данных:

/tmp/demo.txt
/tmp/dir2/file2.txt
/tmp/file1.txt

Чтобы найти и удалить все жесткие ссылки (hard link) на файл с номером inode # 4065089 , запустите:

$ find /tmp/ -xdev -inum 4065089 | xargs rm -v
$ find /tmp/ -xdev -inum 4065089 -print0 | xargs -I {} -0 rm -v {}

Вот пример моей сессии:

Как найти все жесткие ссылки (hard link) в каталоге в Linux

Рисунок 01: Как найти все жесткие ссылки (hard link) на заданное имя файла.

Перевод: Анна Давыдова
Источник: cyberciti.biz

Это интересно:

  • Установка и настройка Apache, PHP, MySQL, phpMyAdmin на Linux (LAMP)
  • Установка и настройка сервера Apache, PHP, MySQL, phpMyAdmin на Windows 10
  • Установка Adobe Photoshop CS6 на Linux (очень простой способ)


Finding symlinks is easy:

% find . -type l

Finding hard links is tricky, because if a subdirectory of the directory in question also has subdirectories then those increase the hard link count. That’s how subdirectories are linked to their parents in UNIX (it’s the .. entry in each subdirectory).

If you only want to find linked files (and not directories), this will work:

% find . -type f ! -links 1

This works because a file that does have hard links will have a link count > 1, and unlinked file has a link count == 1, hence this command looks for all files whose link count <> 1

Alternatively, on newer versions of find you could use:

% find . -type f -links +1

This works for the same reason as above; however, newer versions of find can take +n or -n instead of just a number. This is equivalent to testing for greater than n or less than n, respectively.

There are a lot of answers with scripts to find all hardlinks in a filesystem. Most of them do silly things like running find to scan the whole filesystem for -samefile for EACH multiply-linked file. This is crazy; all you need is to sort on inode number and print duplicates.

With only one pass over the filesystem to find and group all sets of hardlinked files

find dirs   -xdev ! -type d -links +1 -printf '%20D %20i %pn' |
    sort -n | uniq -w 42 --all-repeated=separate

This is much faster than the other answers for finding multiple sets of hardlinked files.
find /foo -samefile /bar is excellent for just one file.

  • -xdev : limit to one filesystem. Not strictly needed since we also print the FS-id to uniq on
  • ! -type d reject directories: the . and .. entries mean they’re always linked.
  • -links +1 : link count strictly > 1
  • -printf ... print FS-id, inode number, and path. (With padding to fixed column widths that we can tell uniq about.)
  • sort -n | uniq ... numeric sort and uniquify on the first 42 columns, separating groups with a blank line

Using ! -type d -links +1 means that sort’s input is only as big as the final output of uniq so we aren’t doing a huge amount of string sorting. Unless you run it on a subdirectory that only contains one of a set of hardlinks. Anyway, this will use a LOT less CPU time re-traversing the filesystem than any other posted solution.

sample output:

...
            2429             76732484 /home/peter/weird-filenames/test/.hiddendir/foo bar
            2429             76732484 /home/peter/weird-filenames/test.orig/.hiddendir/foo bar

            2430             17961006 /usr/bin/pkg-config.real
            2430             17961006 /usr/bin/x86_64-pc-linux-gnu-pkg-config

            2430             36646920 /usr/lib/i386-linux-gnu/dri/i915_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/i965_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/nouveau_vieux_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/r200_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/radeon_dri.so
...

TODO?: un-pad the output with awk or cut. uniq has very limited field-selection support, so I pad the find output and use fixed-width. 20chars is wide enough for the maximum possible inode or device number (2^64-1 = 18446744073709551615). XFS chooses inode numbers based on where on disk they’re allocated, not contiguously from 0, so large XFS filesystems can have >32bit inode numbers even if they don’t have billions of files. Other filesystems might have 20-digit inode numbers even if they aren’t gigantic.

TODO: sort groups of duplicates by path. Having them sorted by mount point then inode number mixes things together, if you have a couple different subdirs that have lots of hardlinks. (i.e. groups of dup-groups go together, but the output mixes them up).

A final sort -k 3 would sort lines separately, not groups of lines as a single record. Preprocessing with something to transform a pair of newlines into a NUL byte, and using GNU sort --zero-terminated -k 3 might do the trick. tr only operates on single characters, not 2->1 or 1->2 patterns, though. perl would do it (or just parse and sort within perl or awk). sed might also work.

If the given file is called /path/to/file and you want to find all hard links to it that exist under the current directory, then use:

find . -samefile /path/to/file 

The above was tested on GNU find. Although -samefile is not POSIX, it is also supported by Mac OSX find and FreeBSD find.

Documentation

From GNU man find:

-samefile name
       File refers to the same inode as name. When -L is in effect, this can include symbolic links.

Differences between find and ls

ls -l lists the number of hard links to a file or directory. For directories, this number is larger than the number of results shown by find . -samefile. The reason for this is explained in the GNU find manual:

A directory normally has at least two hard links: the entry named in
its parent directory, and the . entry inside of the directory. If a
directory has subdirectories, each of those also has a hard link
called .. to its parent directory.

The . and .. directory entries are not normally searched unless they
are mentioned on the find command line.

In sum, ls -l counts the . and .. directories as separate hard links but find . -samefile does not.

Понравилась статья? Поделить с друзьями:
  • Почему вкладка падает в мозиле как исправить
  • Как найти папку binaries
  • Как найти код вай фай на айфоне
  • Найти амулет голдура как открыть дверь
  • Как составить ворчалку