Linux найти символические ссылки

I’m trying to find all of the symlinks within a directory tree for my website. I know that I can use find to do this but I can’t figure out how to recursively check the directories. I’ve tried this command:

it take a while to run, however I’m getting no matches. How do I get this to check subdirectories?

8 Answers 8

This will recursively traverse the /path/to/folder directory and list only the symbolic links:

ls -lR /path/to/folder | grep '^l' 

If your intention is to follow the symbolic links too, you should use your find command but you should include the -L option; in fact the find man page says:

 -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the prop‐ erties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirec‐ tory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is bro‐ ken). Using -L causes the -lname and -ilname predicates always to return false. 

This will probably work: I found in the find man page this diamond: if you are using the -type option you have to change it to the -xtype option:

 l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. 

Источник

Как найти и удалить битые символические ссылки в Linux

Символические ссылки, еще называемые мягкими, существуют не только в Windows, но и в Linux. По сути, символическая ссылка в Linux представляет собой файл, который ссылается на другой файл (в Linux вообще все объекты являются файлами) . Если файл будет удален, перемещен или переименован, указывающая на него символическая ссылка останется на диске, равно как и удаление символической ссылки не приведет к удалению файла.

Читайте также:  Tar linux разбить архив

В этом есть своя польза, например, по символической ссылке можно определить, где раньше располагался тот ли иной файл. С другой стороны, какой смысл держать на диске битые символьные ссылки, пусть даже и занимающие более чем скромное место?

Не будет ли лучшим их удалить? Особой трудности в Linux это не представляет, в той же Ubuntu символические ссылки легко идентифицируются по фиолетовому значку со стрелкой,

Ubuntu link

если же ссылка битая, то на нее «накладывается» еще один значок — крестик в красном кружке.

Битая ссылка

В терминале рабочие симлинки отличаются тем, что имеют бирюзовый цвет, кроме того, после названий мягких ссылок следуют стрелка и имя объекта, на который они ссылаются.

Рабочие симлинки

Если ссылка битая, ее название и название объекта, на который она ссылается, будут иметь красный цвет.

Битые симлинки

Поиск и удаление символических ссылок

Для поиска мягких ссылок в Linux очень удобно использовать команду find, точнее find . -type l , выводящую их список в текущем каталоге и всех вложенных в него папках.

Find

При этом команда с данным набором параметров не различает рабочие и нерабочие ссылки, чтобы получить список только битых ссылок, вместо параметра type нужно использовать параметр -xtype, вот так:

find . -xtype l

Find xtype

Этот способ хорош для поиска битых символических ссылок в домашнем каталоге, в котором вы имеете доступ ко всем файлам, однако, если вы захотите вывести список нерабочих мягких ссылок в корневом каталоге, то вместе с битыми ссылками получите массу ошибок доступа к файлам и папкам, на которые у вас нет разрешений.

Отказано в доступе

SUDO здесь не поможет, решить эту проблему можно сбросив все ошибки в /dev/null .

Добавьте к уже известной команде перенаправление:

find . -xtype l 2>/dev/null

Поскольку символические ссылки занимают очень мало места, их можно вообще не трогать.

Если всё же хотите их удалить, добавьте чрез пробел к указанной выше команде аргумент -delete.

Link delete

Следует, однако, учитывать, что в некоторых случаях символические ссылки могут использоваться не по прямому назначению, например, как индикатор блокировки файла.

В общем, если и удалять битые симлинки, то делать это нужно только в тех системных каталогах, назначение которых вам известно. Так, тест с удалением всех битых символических ссылок в Ubuntu 20.04, установленной на виртуальную машину VirtualBox, нарушило работу дополнений гостевой ОС, в результате чего в виртуальной системе оказалось доступным только разрешение VGA, составляющее всего 640×480 пикселей.

Источник

The symbolic link, also known as symlink or soft link, is the file type that can hold the location of a file or directory in any Linux file system. You have created a couple of Symbolic links in your Linux filesystem, and sometimes there comes a need to list all the symbolic links. This post provides you with a step-by-step guide on how to list all symlinks in a Linux filesystem or a specific Linux directory.

From a couple of ways to list all the symbolic links in a Linux directory, we will follow the reliable and best way using the find command.

Читайте также:  Linux when file was created

Find command comes in handy when finding any type of file or folder in a Linux operating system.

Syntax

To find the symbolic links in any Linux operating system, the syntax is as follows:

is the location or directory name in which you want to search for the symbolic link,

-type is referencing the file type,

while l is representing the link file type.

Alright, let’s have a look at the examples and see how can we get the symbolic links listed in different ways by going through a couple of examples:

Examples

Using the find command, we can list the symlinks from the entire filesystem or in a specific directory. Let’s take a look at each example:

To list all the symlinks from the entire filesystem, you can execute the following find command by providing the “/” as path:

The “/” in the above command represents the entire file system, and the find command will search for the symbolic links from all over the system and list them out in the terminal.

Similarly, if you want to find and list all the symlinks in the current working directory, then simply provide the “.” as a path to the find command as shown below:

In the above command, the “.” tells the find command to find the symlinks in the current working directory.

To list all the symlinks in any directory, just provide the directory path to the find command as shown below:

The find command will look for the symbolic links in the /var/www/ directory only and list out all the symbolic links in that directory.

You might have noticed that all the above commands displayed the symbolic links in the desired directory and showed all the symbolic links from the subdirectories, as well.

So, what if you do not want to go into this much depth? You just want to have the symbolic links in the specified directory. The solution to that problem is not rocket science, and we can quickly mention the depth using the maxdepth flag.

For example, to set the search depth to level one, the find command would go like this:

You can witness the output shown in the screenshot given above. The find command has shown only the symbolic links of the current working directory instead of all the subdirectories.

Conclusion

This post has provided multiple ways and gives a brief explanation on how to list all the symbolic links in the Linux filesystem or a specific Linux directory. Using the find command, we have learned to find and list down all the symbolic links and set the maximum depth level using the maxdepth flag. If you want to learn and explore more about the find command, feel free to read the man page of find using the “man find” command.

Читайте также:  Дистрибутив linux от майкрософт

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.

Источник

🐧 Как перечислить символические ссылки в Linux

Мы уже знаем, что такое Симлинки или Символические ссылки, или Мягкие ссылки и как найти и удалить неработающие Симлинки из нашей системы Linux.

Если вы давно создали несколько символических ссылок и полностью забыли о них, этот быстрый совет поможет вам легко найти их с помощью команды «find».

Список символических ссылок на Linux

Чтобы получить список всех символических или cофт линков в системе Linux, выполните:

  • / – представляет всю файловую систему.
  • -type – относится к типу файла.
  • l – относится к символической ссылке.

Эта команда будет искать все доступные символические ссылки во всей файловой системе.

Это займет некоторое время в зависимости от размера вашей файловой системы.

Пожалуйста, будьте терпеливы!

Если вы хотите ограничить поиск по символической ссылке в определенном каталоге, укажите его путь, как показано ниже.

Например, следующая команда выведет список всех программных ссылок в текущем каталоге:

./snap/multipass/current ./snap/multipass/1597/.config/autostart ./snap/multipass/1597/config/autostart/multipass.gui.autostart.desktop ./snap/multipass/1784/.config/autostart ./snap/multipass/1784/config/autostart/multipass.gui.autostart.desktop ./.local/share/webkitgtk/databases/indexeddb/v0 find: ‘./.dbus’: Permission denied ./.config/spyder-py3/spyder.lock ./Downloads/Tor browser/Browser/.config/ibus/bus ./.mozilla/firefox/htoypxlg.default-1563118799416/lock

Если вы хотите искать символические ссылки в другом каталоге, замените точку (.) на путь к каталогу.

Если вы хотите получить подробный вывод, включая метки времени, права доступа к файлам, владельца и группу, используйте следующую команду:

4458987 0 lrwxrwxrwx 1 sk sk 4 Mar 6 13:58 ./snap/multipass/current -> 1784 11927799 0 lrwxrwxrwx 1 sk sk 19 Mar 5 11:20 ./snap/multipass/1597/.config/autostart -> ../config/autostart 11932200 4 lrwxrwxrwx 1 sk sk 72 Feb 27 15:30 ./snap/multipass/1597/config/autostart/multipass.gui.autostart.desktop -> /snap/multipass/1597/usr/share/multipass/multipass.gui.autostart.desktop 11534358 0 lrwxrwxrwx 1 sk sk 19 Mar 17 11:51 ./snap/multipass/1784/.config/autostart -> ../config/autostart 11666096 4 lrwxrwxrwx 1 sk sk 72 Mar 6 13:58 ./snap/multipass/1784/config/autostart/multipass.gui.autostart.desktop -> /snap/multipass/1784/usr/share/multipass/multipass.gui.autostart.desktop 5246237 0 lrwxrwxrwx 1 sk sk 51 Feb 12 20:14 ./.local/share/webkitgtk/databases/indexeddb/v0 -> /home/sk/.local/share/webkitgtk/databases/indexeddb find: ‘./.dbus’: Permission denied 4459630 0 lrwxrwxrwx 1 sk sk 5 Jan 24 17:39 ./.config/spyder-py3/spyder.lock -> 18461 4340805 0 lrwxrwxrwx 1 sk sk 25 Feb 15 15:21 ./Downloads/Tor\ browser/Browser/.config/ibus/bus -> /home/sk/.config/ibus/bus 4328111 0 lrwxrwxrwx 1 sk sk 20 Mar 17 11:56 ./.mozilla/firefox/htoypxlg.default-1563118799416/lock -> 192.168.225.37:+2642

Как вы могли заметить в приведенных выше выходных данных, команда find ищет символические ссылки в текущем каталоге и его подкаталогах.

Если вы хотите перечислить все символические ссылки на один уровень в текущем каталоге, используйте флаг maxdepth, как показано ниже.

$ find . -type l -printf '%p -> %l\n'
./snap/multipass/current -> 1784 ./snap/multipass/1597/.config/autostart -> ../config/autostart ./snap/multipass/1597/config/autostart/multipass.gui.autostart.desktop -> /snap/multipass/1597/usr/share/multipass/multipass.gui.autostart.desktop ./snap/multipass/1784/.config/autostart -> ../config/autostart ./snap/multipass/1784/config/autostart/multipass.gui.autostart.desktop -> /snap/multipass/1784/usr/share/multipass/multipass.gui.autostart.desktop ./.local/share/webkitgtk/databases/indexeddb/v0 -> /home/sk/.local/share/webkitgtk/databases/indexeddb find: ‘./.dbus’: Permission denied ./.config/spyder-py3/spyder.lock -> 18461 ./Downloads/Tor browser/Browser/.config/ibus/bus -> /home/sk/.config/ibus/bus ./.mozilla/firefox/htoypxlg.default-1563118799416/lock -> 192.168.225.37:+2642

Для более подробной информации обратитесь к справочным страницам.

Источник

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