Найти все жесткие ссылки linux

I have two external disks that has the same files. One is encrypted, the other is not. The encrypted one has a lot less space left than the non encrypted, I now assume that it is because of hardlinks on the non encrypted disks. So I would like to check, if there are any hardlinked files that might be doubled on the encrypted disk. How can I identify a hardlink? If you have any other ideas what the reason for the free space issue could be, I’am open to ideas. Is it possible that the files need more space because of the encryption?

Please edit your original question, when the two external disks are connected and their partitions mounted, in order to show the output of the following commands for the two file systems (the encrypted one and the un-encrypted one), df ; sudo lsblk -f ; sudo lsblk -m ; Indent each line 4 spaces to render the output as code .

4 Answers 4

That will show all regular files that have more than one link (name) to them. It will not tell you which names are linked to the same file, for that you could use -samefile or -inum , e.g. find -samefile «$somefile»

In the technical sense, all files (file names) are (hard) links, it’s just that files with more than one link pointing to them are interesting in this sense. But even in those cases, there’s no way to say that one of them is the «proper» file, and the other a link, the links are equal.

$ touch a b c $ ln b b2 ; ln c c2 $ find -type f -links +1 ./c2 ./b ./b2 ./c $ find -samefile b ./b ./b2 

-links +1 is a GNU extension. For better portability (POSIX compliance), use the equivalent \! -links 1 as in: find . -type f \! -links 1 . Also, -samefile is likewise a GNU extension for which there is no simple POSIX equivalent (at least not within find ).

Читайте также:  Узнать конфигурацию сервера linux

Ah, that is true. I frequent Unix & Linux SE and tend to forget that portability isn’t as much of a concern over here. 🙂

@ilkkachu’s and @barrycarter’s answers are good. This answer is an alternative, that describes some results with more details.

  • If the linked in the same directory tree, you will find them directly.
  • Otherwise you can search in the whole file system from the mount point, but only within the same file system using -xdev , which is important if you search the root partition / and there are other mounted partitions.
$ sudo find / -xdev -type f -links +1 -ls | sort -n > hard-links-in-root.txt 

The following is an example, where one hard linked pair is found in the current directory, and two hard linked matches are found in another directory by searching from the mount point /media/multimed-2 of the data partition.

$ sudo find . -xdev -type f -links +1 -ls | sort -n 5242881 648 -rw-rw-r-- 2 olle nio 657936 jun 30 2015 ./like-this.png 5242882 940 -rw-rw-r-- 2 olle nio 957688 jun 30 2015 ./from-here.png 14843905 1620 -rw-r--r-- 2 olle nio 1652803 jun 30 2015 ./img_4810.jpg 14843905 1620 -rw-r--r-- 2 olle nio 1652803 jun 30 2015 ./mid-sommer-night_4810.jpg $ find /media/multimed-2/ -samefile ./like-this.png /media/multimed-2/Photos/2015/06/30/like-this.png /media/multimed-2/Bilder/kartor/like-this.png $ find /media/multimed-2/ -samefile ./from-here.png /media/multimed-2/Photos/2015/06/30/from-here.png /media/multimed-2/Bilder/kartor/from-here.png 

Other causes why different amount of drive space is used

  • Different file systems (ext4, NTFS, FAT32 . )
  • Different partition size, which causes differences in the overhead (meta-data).
  • Different sector size on the drive (maybe?)

Источник

У меня есть файл с именем /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

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

Оставьте ответ Отменить ответ

📅 С 20 по 22 апреля пройдут незабываемые битвы среди кибер-гладиаторов в мире информационной безопасности!

Открыта регистрация команд по ссылке .

Источник

How can we find all hard links to a given file? I.e., find all other hard links to the same file, given a hard link? Does filesystem keep track of the hard links to a file? The inode of a file only stores the number of hard links to the file, but not the hard links, right?

1 Answer 1

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

-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.

Источник

Оцените статью
Adblock
detector