Как рекурсивно изменить права доступа к файлу в Linux
Если вы используете Linux в качестве основной операционной системы или управляете серверами Linux, вы столкнетесь с ситуацией, когда попытаетесь создать или отредактировать файл и получите ошибку «Permission deny». Как правило, ошибки, связанные с недостаточными разрешениями, можно решить, установив правильные права доступа или владельца .
Linux — это многопользовательская система, и доступ к файлам контролируется с помощью разрешений, атрибутов и владельцев файлов. Это гарантирует, что только авторизованные пользователи и процессы могут получить доступ к файлам и каталогам.
Для получения дополнительной информации о правах доступа к файлам см. «Команда Umask в Linux» .
В этой статье мы объясним, как рекурсивно изменять права доступа к файлам и каталогам.
Chmod Рекурсивный
Команда chmod позволяет изменять права доступа к файлам в символьном или числовом режиме.
Чтобы рекурсивно работать со всеми файлами и каталогами в данном каталоге, используйте команду chmod с параметром -R , ( —recursive ). Общий синтаксис для рекурсивного изменения прав доступа к файлу следующий:
Например, чтобы изменить права доступа для всех файлов и подкаталогов в каталоге /var/www/html на 755 вы должны использовать:
Режим также можно указать с помощью символьного метода:
Только root, владелец файла или пользователь с привилегиями sudo могут изменять права доступа к файлу. Будьте особенно осторожны при рекурсивном изменении разрешений файлов.
Использование команды find
Как правило, файлы и каталоги не должны иметь одинаковые разрешения. Большинству файлов не требуется разрешение на выполнение, тогда как вы должны установить разрешения на выполнение для каталогов, чтобы изменить их.
Наиболее распространенный сценарий — рекурсивное изменение разрешений файла веб-сайта на 644 и разрешений каталога на 755 .
Команда find ищет файлы или каталоги в /var/www/html и передает каждый найденный файл или каталог команде chmod для установки разрешений.
При использовании find с -exec команда chmod запускается для каждой найденной записи. Используйте команду xargs чтобы ускорить операцию, передав сразу несколько записей:
Выводы
Команда chmod с параметрами -R позволяет рекурсивно изменять права доступа к файлу.
Чтобы рекурсивно установить разрешения для файлов в зависимости от их типа, используйте chmod в сочетании с командой find .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Chmod recursively
I have an archive, which is archived by someone else, and I want to automatically, after I download it, to change a branch of the file system within the extracted files to gain read access. (I can’t change how archive is created).
The directories originally come with multiple but all wrong flags, they may appear as:
Those are just the few I’ve discovered so far, but could be more.
find errors when tries to look into a directory with no x permission, and so doesn’t pass it to chmod . What I’ve been doing so far, is manually change permissions on the parent directory, then go into the child directories and do the same for them and so on. But this is a lot of hand labour. Isn’t there some way to do this automatically?
How can I recursively change the permissions of files and directories?
I have ubuntu installed on my local computer with apache / php / mysql.
I now have a directory at /var/www — inside which I have several of my ongoing projects. I also work with opensource ( drupal, magento, sugarcrm ).
The problem I am facing is changing file permission with terminal. Sometime I need to change the permission of entire folder and its subsequent sub-folders and files. I have to individually change using
How can I do this recursively.
Also why do I have to always do it 777, I tried 755 for folders and 644 for files, but that won’t work.
5 Answers 5
Just add the -R option to recursively change the permissions of files. An example, recursively add read and write permissions for the owner and group on foldername :
Permissions will be like 664 or 775.
Setting the permissions to 777 is highly discouraged. You get errors in either Apache or your editor regarding permissions because apache runs under a different user ( www-data ) than you.
If you want to write to /var/www , add yourself to the www-data group and set umask+permissions accordingly.
Linux — How to recursively chmod a folder?
How can I recursively chmod everything inside of a folder?
e.g. I have a folder called var which contains many subfolders and files.
How can I apply chmod 755 recursively to this folder and all its contents?
5 Answers 5
Please refer to the manual ( man chmod ):
chmod -R 755 /path/to/directory would perform what you want.
However…
You don’t usually want to 755 all files; these should be 644, as they often do not need to be executable. Hence, you could do find /path/to/directory -type d -exec chmod 755 <> \; to only change directory permissions. Use -type f and chmod 644 to apply the permissions to files.
This will overwrite any existing permissions. It’s not a good idea to do it for /var — that folder has the correct permissions set up by the system already. For example, some directories in /var require 775 permissions (e.g., /var/log ).
So, before doing sudo chmod — particularly on system folders — pause and think about whether that is really required.