На чтение 4 мин Просмотров 4.3к. Опубликовано 20.06.2021
Символьная ссылка, также известная как символическая ссылка или программная ссылка, — это тип файла, который может содержать местоположение файла или каталога в любой файловой системе Linux. Вы создали пару символических ссылок в файловой системе Linux. И иногда возникает необходимость перечислить все символические ссылки. Этот пост предоставляет вам пошаговое руководство о том, как составить список всех символических ссылок в файловой системе Linux или в конкретном каталоге Linux.
Из пары способов перечислить все символические ссылки в каталоге Linux, мы рассмотрим самый надежный и лучший способ, используя команду find.
Содержание
- Список всех символических ссылок с помощью команды поиска
- Синтаксис
- Примеры
- Список всех символических ссылок из всей файловой системы
- Список всех символических ссылок в текущем рабочем каталоге
- Список всех символических ссылок в любом каталоге
- Список всех символических ссылок в каталоге с помощью флага Maxdepth
- Заключение
Список всех символических ссылок с помощью команды поиска
Команда «Найти» пригодится при поиске любого типа файла или папки в операционной системе Linux.
Синтаксис
Чтобы найти символические ссылки в любой операционной системе Linux, используйте следующий синтаксис:
$ sudo find <path> -type l
В приведенной выше команде
<path> — это место или имя каталога, в котором вы хотите искать символическую ссылку,
-type ссылается на тип файла,
while l представляет тип файла ссылки.
Хорошо, давайте посмотрим на примеры и посмотрим, как мы можем получить список символических ссылок по-разному, рассмотрев пару примеров:
Примеры
Используя команду find, мы можем перечислить символические ссылки из всей файловой системы или в определенном каталоге. Давайте посмотрим на каждый пример:
Список всех символических ссылок из всей файловой системы
Чтобы вывести список всех символических ссылок из всей файловой системы, вы можете выполнить следующую команду поиска, указав «/» в качестве пути:
Символ «/» в приведенной выше команде представляет всю файловую систему, а команда find будет искать символические ссылки по всей системе и выводить их список в терминале.
Список всех символических ссылок в текущем рабочем каталоге
Точно так же, если вы хотите найти и перечислить все символические ссылки в текущем рабочем каталоге, просто укажите «.» как путь к команде поиска, как показано ниже:
В приведенной выше команде символ «.» сообщает команде find найти символические ссылки в текущем рабочем каталоге.
Список всех символических ссылок в любом каталоге
Чтобы перечислить все символические ссылки в любом каталоге, просто укажите путь к каталогу для команды find, как показано ниже:
$ sudo find /var/www/ -type l
Команда find будет искать символические ссылки только в каталоге / var / www / и перечислять все символические ссылки в этом каталоге.
Список всех символических ссылок в каталоге с помощью флага Maxdepth
Вы могли заметить, что все вышеперечисленные команды отображали символические ссылки в нужном каталоге. А также отображали все символические ссылки из подкаталогов.
Итак, что, если вы не хотите вдаваться в подробности? Вы просто хотите иметь символические ссылки в указанном каталоге. Решение этой проблемы не в ракетостроении, и мы можем быстро указать глубину, используя флаг maxdepth.
Например, чтобы установить глубину поиска на один уровень, команда find будет выглядеть так:
$ sudo find . -maxdepth 1 -type l
Вы можете увидеть результат, показанный на скриншоте выше. Команда find показала только символические ссылки текущего рабочего каталога вместо всех подкаталогов.
Заключение
В этом посте представлено несколько способов и дается краткое объяснение того, как перечислить все символические ссылки в файловой системе Linux или в конкретном каталоге Linux. Используя команду find, мы научились находить и перечислять все символические ссылки и устанавливать максимальный уровень глубины с помощью флага maxdepth. Если вы хотите узнать больше о команде find, не стесняйтесь читать справочную страницу find с помощью команды «man find».
On this question or on this one (for example) you will get solutions on how to look for symlinks pointing to a given directory (let’s call it /dir1
), while I am interested to symbolic links possibly pointing to any file/folder inside /dir1
.
I want to delete such directory but I am not sure that I am safe to do so, as on an other directory (let’s call it /dir2
), I may have symlinks pointing to inner parts of /dir1
.
Further, I may have created these symlinks using absolute or relative paths.
My only help is that I know the symlinks I want to check are on a mounted filesystem, on /dir2
.
asked Aug 6, 2016 at 9:36
You can find all the symbolic links using:
find / -type l
you might want to run this as root in order to get to every place on the disc.
You can expand these using readlink -f
to get the full path of the link and you should be able to grep
the output against the target directory that you are considering for deletion:
find / -type l -exec readlink -f {} + | grep -F /dir2
Using find / -type l -printf '%ln'
doesn’t work as you get relative links like ../tmp/xyz
which might be pointing to your target dir, but are not matched because they are not fully expanded.
answered Aug 6, 2016 at 9:53
AnthonAnthon
77.8k42 gold badges164 silver badges221 bronze badges
3
In my case, the accepted answer wasn’t useful (because it didn’t output the link source). Here is what worked for me.
I worked around it using two -exec
clauses:
find /home/ -type l -exec readlink -nf {} ';' -exec echo " -> {}" ';' | grep "/dir2"
answered Nov 20, 2018 at 14:41
2
With zsh
:
print -rC1 /dir2/**/*(ND@e['[[ $REPLY:P = /dir1(/*|) ]]'])
Broken down:
print -rC1
: prints its argumentsr
aw on1
C
olumn. Here, the arguments will be those generated from the following glob. Replace withls -ld
to get more information about each symlink¹**/
: any level of subdirectories (recursive globbing)*
: file with any name (made of any number of characters, though zsh’s*
like that of most shells will also allow non-characters).(...)
: glob qualifiers to further qualify the matching on other criteria than just the name of the filesN
: enablenullglob
for that one glob (won’t fail if there’s no match, just pass an empty list toprint
which will print nothing).D
: enabledotglob
: also consider hidden files.@
: restrict to files of type symlink.e['code']
: select files for which thecode
evaluates to true. Inside thecode
, the file being considered is stored in$REPLY
.$REPLY:P
: gets the absolute and canonical (symlink free) path to the file (similar to what therealpath()
standard function does).[[ string = pattern ]]
returns true if the string matches the pattern (from ksh)./dir1(/*|)
as a pattern matches on/dir1
alone or/dir1/
followed by anything.
¹ with the caveat that if there’s not matching file, that will list the current working directory. With ls
, it would be better to remove the N
glob qualifier
answered Nov 20, 2018 at 15:32
Stéphane ChazelasStéphane Chazelas
511k90 gold badges990 silver badges1473 bronze badges
Depending on your circumstances, you could delete the directory, then delete any resultant invalid symlinks with the following:
find -xtype l -delete
The xtype test returns ‘l’ if the symlink is broken.
answered Sep 16, 2020 at 20:19
0
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.
Then try this:
find -L /var/www/ -type l
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.
Then:
find -L /var/www/ -xtype l
Asked
10 years, 10 months ago
Viewed
9k times
I know there are ways to figure out actual physical location of a file by following the symbolic link. But is it possible to know where is the symbolic link if you know the physical location of the file and you are sure that there is a symbolic link.
asked Jul 12, 2012 at 15:29
1
The filesystem simply does not contain that information, to the best of my knowledge. That means your only way is to traverse the filesystem looking at all the symlinks and marking those that point to your desired file.
Not ideal, I know. The symlinks tool (apt-get install symlinks) will help you do this. Be careful, it doesn’t traverse filesystem boundaries!
answered Jul 12, 2012 at 15:33
MiquelMiquel
15.4k8 gold badges53 silver badges87 bronze badges
2
Can be done with python as well:
$ python -c "import os,sys; print 'n'.join([os.path.join(sys.argv[1],i) for i in os.listdir(sys.argv[1]) if os.path.islink(os.path.join(sys.argv[1],i))])" /path/to/dir
Sample run:
$ python -c "import os,sys; print 'n'.join([os.path.join(sys.argv[1],i) for i in os.listdir(sys.argv[1]) if os.path.islink(os.path.join(sys.argv[1],i))])" /etc
/etc/vtrgb
/etc/printcap
/etc/resolv.conf
/etc/os-release
/etc/mtab
/etc/localtime
This can be extended to be recursive via os.walk
function, but it’s sufficient to use simple list generation for listing links in a single directory as I showed above.