Linux link all files in directory

Символические и жесткие ссылки Linux

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

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

Символические ссылки

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

Вот основные особенности символических ссылок:

  • Могут ссылаться на файлы и каталоги;
  • После удаления, перемещения или переименования файла становятся недействительными;
  • Права доступа и номер inode отличаются от исходного файла;
  • При изменении прав доступа для исходного файла, права на ссылку останутся неизменными;
  • Можно ссылаться на другие разделы диска;
  • Содержат только имя файла, а не его содержимое.

Теперь давайте рассмотрим жесткие ссылки.

Жесткие ссылки

Этот тип ссылок реализован на более низком уровне файловой системы. Файл размещен только в определенном месте жесткого диска. Но на это место могут ссылаться несколько ссылок из файловой системы. Каждая из ссылок — это отдельный файл, но ведут они к одному участку жесткого диска. Файл можно перемещать между каталогами, и все ссылки останутся рабочими, поскольку для них неважно имя. Рассмотрим особенности:

  • Работают только в пределах одной файловой системы;
  • Нельзя ссылаться на каталоги;
  • Имеют ту же информацию inode и набор разрешений что и у исходного файла;
  • Разрешения на ссылку изменяться при изменении разрешений файла;
  • Можно перемещать и переименовывать и даже удалять файл без вреда ссылке.

Использование ссылок в Linux

Теоретические отличия вы знаете, но осталось закрепить все это на практике, поэтому давайте приведем несколько примеров работы со ссылками в Linux. Для создания символических ссылок существует утилита ln. Ее синтаксис очень прост:

$ ln опции файл_источник файл_ссылки

Рассмотрим опции утилиты:

  • -d — разрешить создавать жесткие ссылки для директорий суперпользователю;
  • -f — удалять существующие ссылки;
  • -i — спрашивать нужно ли удалять существующие ссылки;
  • -P — создать жесткую ссылку;
  • -r — создать символическую ссылку с относительным путем к файлу;
  • -s — создать символическую ссылку.

Создание символических ссылок

Сначала создайте папку test и перейдите в нее:

mkdir test && cd test

Читайте также:  No such file or directory ��� ��������� linux

Затем создайте файл с именем source с каким-либо текстом:

echo «текст текст текст текст» > source
$ cat source

Файл готов, дальше создадим символическую ссылку Linux, для этого используется команда ln с опцией -s:

ln -s source softlink

Попробуем посмотреть содержимое файла по ссылке:

Как видите, нет никакой разницы между ней и исходным файлом. Но утилита ls покажет что это действительно ссылка:

Несмотря на то, что содержимое одинаковое, здесь мы видим, что адрес иноды и права доступа к файлам отличаются, кроме того, явно показано что это символическая ссылка Linux.

Теперь удалите исходный файл и посмотрите что будет:

Вы получите ошибку, что такого файла не существует, потому что мы действительно удалили исходный файл. Если вы удалите ссылку, то исходный файл останется на месте.

Создание жестких ссылок

Снова создайте файл source с произвольным текстом:

echo «текст текст текст текст» > source
$ cat source

Теперь создадим жесткую ссылку Linux. Для этого достаточно вызвать утилиту без параметров:

ln source hardlink

Посмотрите содержимое файла:

Данные те же самые, а если мы посмотрим вывод утилиты ls, то увидим что inode и права доступа тоже совпадают:

Если для одного из файлов поменять разрешения, то они изменяться и у другого. Теперь удалите исходный файл:

Затем посмотрите содержимое:

Как видите, ничего не произошло и ссылка по-прежнему указывает на нужный участок диска, это главное отличие жесткой ссылки от символической. Мы можем сделать вывод, что жесткая ссылка linux это обычный файл. Каждый файл имеет как минимум одну ссылку, но для некоторых мы можем создать несколько ссылок.

Выводы

Это все, что вам было необходимо знать про символические и жесткие ссылки linux. Надеюсь, вы получили общее представление об этих возможностях файловой системы и сможете использовать их для решения своих задач.

На завершение видео про ссылки в Linux:

Источник

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 5 years ago .

I’m trying to symlink all files in a directory to a target directory, by doing:

Problem is when I go into the target-directory, I’m seeing this ‘*’, an asterisk in quotes, instead of all the files in the first directory. What am I doing wrong? Thanks.

3 Answers 3

Normally, what’d happen when you run ln -s /directory/* /target-directory is that the shell would expand /directory/* into a list of the (currently existing, visible) files in /directory/, and then pass that to ln in its argument list. The result would be equivalent to something like ln -s /directory/file1.txt /directory/file3.pdf /directory/file3.c /target-directory . Note that the ln command would not see the «*», and so would not include it in either the link source or target name.

Since «*» is being used as the link name, it’s not getting expanded. There are a couple of reasons this might happen:

You might have the noglob shell option set. But you said in the comments that’s not the case.

The shell expansion might not have matched any files, in which case the shell will simply pass it unchanged to ln , giving the result you describe. You said you created a file in the source directory, but did you re-test after doing that? Another possibility is that there’s a typo in the directory path, so it’s not finding a matching directory (let alone any files in it).

Oh, one more note: you said when you go to the target directory, you see an asterisk in quotes. Exactly how are you looking? Because if you’re just using ls , it should not include quotes in the listing unless they’re actually part of the filename. [Edit: Mark Plotnick pointed out that some versions of GNU ls do add quotes to some filenames.] I have no idea how the command you gave could add quotes to the filename.

Читайте также:  Переводчик сократ для windows 10

Источник

Symbolic links can be made to directories as well as to files on different filesystems or different partitions.

  • symbolic links (also known as “soft links” or “symlinks”): Refer to a symbolic path indicating the abstract location of another file.
  • hard links : Refer to the specific location of physical data.

Soft links are created with the ln command. For example, the following would create a soft link named link1 to a file named file1, both in the current directory
$ ln -s file1 link1
To verify new soft link run:
$ ls -l file1 link1
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

From the above outputs it is clear that a symbolic link named ‘link1’ contains the name of the file named ‘file1’ to which it is linked.

How to use the ln command

So the syntax is as follows to create a symbolic link in Unix or Linux, at the shell prompt:
$ ln -s < source-filename >< symbolic-filename >

For example create a softlink for /webroot/home/httpd/test.com/index.php as /home/vivek/index.php, enter the following command:
$ ln -s /webroot/home/httpd/test.com/index.php /home/vivek/index.php
$ ls -l
Sample outputs:

You can now edit the soft link named /home/vivek/index.php and /webroot/home/httpd/test.com/index.php will get updated:
$ vi /home/vivek/index.php
Your actual file /webroot/home/httpd/test.com/index.php remains on disk even if you deleted the soft link /home/vivek/index.php using the rm command:
$ rm /home/vivek/index.php ## ##
## But original/actual file remains as it is ##
$ ls -l /webroot/home/httpd/test.com/index.php

The syntax remains same:
$ ln -s
For example, create a symbolic link from the /home/lighttpd/http/users/vivek/php/app/ directory to the /app/ directory you would run:
$ ln -s /home/lighttpd/http/users/vivek/php/app/ /app/
Now I can edit files using /app/
$ cd /app/
$ ls -l
$ vi config.php

Pass the -f to the ln command to overwrite links:
ln -f -s /path/to/my-cool-file.txt link.txt

Use the rm command to delete a file including symlinks:
rm my-link-name
unlink /app/
rm /home/vivek/index.php

Getting help about the ln command

Type the following ln command:
$ man ln
$ ln —help

ln command option Description
—backup make a backup of each existing destination file
-b like —backup but does not accept an argument
-d allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser)
-f remove existing destination files
-i prompt whether to remove destinations
-L dereference TARGETs that are symbolic links
-n treat LINK_NAME as a normal file if it is a symbolic link to a directory
-P make hard links directly to symbolic links
-r create symbolic links relative to link location
-s make symbolic links instead of hard links
-S override the usual backup suffix
-t specify the DIRECTORY in which to create the links
-T treat LINK_NAME as a normal file always
-v print name of each linked file
—help display this help and exit
—version output version information and exit
Читайте также:  Setting the path environment variable windows

Conclusion

You learned how to create a symbolic link in Linux using the ln command by passing the -s option. See ln command man page here for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Recursively list all files in a directory including files in symlink directories

Suppose I have a directory /dir inside which there are 3 symlinks to other directories /dir/dir11 , /dir/dir12 , and /dir/dir13 . I want to list all the files in dir including the ones in dir11 , dir12 and dir13 .

To be more generic, I want to list all files including the ones in the directories which are symlinks. find . , ls -R , etc stop at the symlink without navigating into them to list further.

8 Answers 8

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

You can also accomplish this with

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

as -follow has been deprecated.

How about tree? tree -l will follow symlinks.

Disclaimer: I wrote this package.

-type f means it will display real files (not symlinks)

-follow means it will follow your directory symlinks

-print will cause it to display the filenames.

If you want a ls type display, you can do the following

From the find manpage:

If you find you want to only follow a few symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.

I knew tree was an appropriate, but I didn’t have tree installed. So, I got a pretty close alternate here

properties 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 subdirectory pointed to by the symbolic link will be searched.

-L dereferences symbolic links. This will also make it impossible to see any symlinks to files, though — they’ll look like the pointed-to file.

in case you would like to print all file contents: find . -type f -exec cat <> +

Not the answer you’re looking for? Browse other questions tagged linux or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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