Understand Linux File Permissions and how to use chmod.
![]()
If you are here you probably want to understand more about Linux file permissions or the command “chmod”.
But it’s not only for Linux, this concept applies to all platforms, Windows, Mac, and any other operating system.
Learning this will give you more knowledge about how this works and increase how you can handle permissions in general.
But, here we will follow the command that is used for Unix / Linux based systems only.
File Permission?
All the files that you have in your system will have a set of permissions of who can read, write or execute.
This is in place not only to make sure you can manage your files, but if you have more than one user on your computer, or, you are configuring a server to set who can see that or change that file.
Let’s visualize this:
These are some file permissions on my system, on your Linux / Unix based system, you can check and visualize which permissions you have for a file, this “drwxr-xr-x” is the permissions that are set to this file, “felipegarcia” is the user that owns the file or created the file, “staff” is the group that this file belongs.
Before go talk more about the permissions, it’s important to understand that a file is always set to a user and a group and other users, which I will discuss later.
The user and the group can have the same name, but they are still different things.
The important thing to notice is, you can have a group that has a set of permissions, like, only read permission, and adds as many users you want to that group. For all the files that are set to belong to that group, the users will be able to only read that file, not write or execute.
For the user, it’s more simple, as the permission set to that user will be only to that user.
Now let’s dig into the permissions, to better visualize here is an indication of how you should visualize all those letters.
As you can see, we should split all those letters into 4 “groups”, at the beginning is 1 character, and the other 3 will be split into 3 groups with 3 characters each, that…
How to Change Permissions and Owners in Linux Using the Command Line
In this tutorial, you will learn how to use the Linux commands chmod and chown to change permissions and owners. As a result, you will have better management in team-based projects.

Why Change Permissions and Owners in Linux
Linux is a multi-user operating system, so more than one person can work on the same computer at the same time. What’s great, the system can be accessed locally or remotely. That’s why developers often use this OS for group projects.
In such a large environment, we need to set file permissions and ownership, so only specific users can access our data. This way, we can protect sensitive information and prevent unwanted changes from happening.
Fortunately, thanks to chmod and chown commands, it is easy to edit permissions and owners in Linux. But before we begin to learn how to use them, make sure you have access to the command line. You can launch it by pressing Ctrl + Alt + T.
How to Change File and Folder Permissions in Linux
We will be using the chmod command to change file and folder permissions in Linux. But first, you need to be aware that there are three types of users who can interact with a file:
- Owner — the user who creates and owns a file or folder.
- Group — all users who are members of the same group.
- Others — all other users on the system who are neither the owner nor members of a group.
To see permissions and owners of a specific file, you can run this command:
The result will look like this:
Let’s break the output down to see what each field means:
- “-rwxrw-rw-“ — this part of the line represents the file permissions. To understand it better, we have to divide it into four groups: (–), (rwx), (rw-), and (rw-).
- The first group indicates the file type. Our example shows a hyphen, which represents a regular file. If we are inspecting a directory, the hyphen will be replaced by d.
- The three characters after the file type represent the owner’s file permissions. In this example, we can see that the owner can read (r), write (w), and execute (x) the file.
- The next three characters are the group’s file permissions. We can conclude that the group can read (r) and write (w), but cannot execute the file. This is because the last character is a hyphen instead of the letter x.
- The last group is others’ file permissions. Based on our example, this type of user cannot execute the file, but they are allowed to read and write.
How to Use chmod Command
Let’s say someone in the group is getting bash: permission denied error and we want to change Linux file permissions from -rwxrw-rw- to -rwx-r–r–. Simply enter this line:
By executing this command, the owner can read, write, and execute the file (rwx). However, group and others are only allowed to read (r–).
At this point, you might wonder why we are using a three-digit number (744) after the chmod command.
The number determines the file permissions. Read, write, and execute are represented by a numerical value:
- r (read) – 4
- w (write) – 2
- x (execute) – 1
So if you want to give all permissions (rwx) to a user, we need to add read (4), write (2), and execute (1). Therefore, rwx is equal to 7.
Meanwhile, since group and others are only allowed to read the file, we give them 4.
Remember, the owner’s permissions always come first, then followed by group and others. That’s why we enter 744.
Pro Tip
If you don’t want to give any permission to a user, enter 0 into the corresponding spot.
Here is a list of the most common file permissions:
Conclusion
In this tutorial, you have learned how to use chmod and chown commands to change permissions and owners in Linux. We also provided the basic syntax and several useful options that you can combine with either of these commands.
To learn more about Linux command line, you can read our article on basic bash commands.
If you have any questions, feel free to comment below!
Learn More Linux Commands for File Management
Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.
Related tutorials

How to Host a Discord Bot: Making and Deploying Your Own Bot to VPS in 2023
Adding bots to your Discord server lets you automate tasks and add new features. While there are many popular Discord bots that are ready to use, you.

How to Configure Your Ubuntu Firewall with UFW and Set Firewall Rules
When configured improperly, your Linux virtual private server (VPS) is vulnerable to cyber attacks. Even if your hosting provider installs robust.

How to Use GitHub Copilot: Setting Up and Learning Various Useful AI Coding Methods
GitHub Copilot is a code suggestion tool designed to act as your AI pair programmer, helping developers code more quickly and accurately. Thanks to.
Права доступа к файлам и папкам
Поговорив о пользователях и группах, самое время вспомнить про права доступа, которые для них настраиваются. Общая схема прав одинакова и для файлов, и для папок. Вы уже видели, как система отображает права доступа, в выводе команды ls -l , которая показывает содержимое директории:
Первые 10 символов содержат информацию о правах к файлу или каталогу.
права пользователей группы-владельца
права всех остальных пользователей
Далее идёт имя пользователя-владельца и группы -владельца.
файл принадлежит пользователю root
файл принадлежит группе root
Исходя из этого, иерархия доступа на уровне пользователей разбивается следующим образом: права пользователя-владельца, права участников группы-владельца и права всех остальных.
Соответственно, для каждой категории указывается, какие операции с файлом ей доступны: чтение (r), запись (w) или выполнение (x) — для исполняемых файлов. Для директорий параметры те же, но обозначают немного другое: просмотр директории (r), создание папок / файлов (w) внутри директории, переход в директорию (x).
Каждый из этих уровней доступа можно выразить в восьмеричной системе с помощью числового значения: 4 (r), 2 (w), 1 (x). Вот так мы и получаем общую схему прав:
a — любые пользователи u — права пользователя g — права группы o — права всех остальных r w x r w x r w x 4 2 1 4 2 1 4 2 1 Для отображения уровня прав помимо формата rwxrwxrwx используется упомянутый восьмеричный формат. Для этого достаточно сложить все уровни прав по категориям:
Теперь можно перейти к инструментам, которые позволяют управлять правами на файлы и директории.
Смена владельца файла или директории
Для смены владельца доступны два инструмента. Первый — chown , позволяет изменить пользователя и группу файла или папки:
Если не указывать группу, изменится только пользователь-владелец. Если не указывать пользователя ( :[новая группа] ), изменится только группа-владелец.
При изменении прав на директории можно использовать параметр -R . Он рекурсивно изменит владельца всех вложенных директорий и файлов. Представим, что нам нужно предоставить права на папку new-user для одноимённого пользователя и его группы. Команда для этого будет выглядеть так:
Второй инструмент — chgrp . В отличие от первого, меняет только группу-владельца:
Как и chown, может работать рекурсивно с помощью ключа -R .
Смена прав доступа к файлу или директории
Для работы непосредственно с правами используется команда chmod :
При работе с директориями опция -R позволит изменить права на все вложенные файлы и папки.
Настройки прав в chmod можно определять двумя способами:
Указав категорию ( u — пользователь-владелец, g — группа-владелец, o — другие пользователи, a — все пользователи), модификатор ( + , — , = ) и, соответственно, нужные права ( r , w , x ).
Например, представим, что у нас есть файл example.txt с максимальным уровнем прав для всех категорий пользователей:
Допустим, мы не хотим, чтобы кто-то в принципе мог запускать этот файл на выполнение. В таком случае нам нужно убрать параметр «x» из прав всех категорий пользователей сразу. Это можно сделать так:
Представим, что потом мы решили вернуть владельцу права на запуск файла. То есть нам нужно добавить параметр «x» в категорию пользователя-владельца:
Если вдруг мы захотим изменить весь набор параметров для отдельной категории разом, это будет выглядеть следующим образом:
Указав права в виде числового значения. Возможно, это не так прозрачно, но зато быстрее. В качестве параметра нам нужно передать это самое цифровое выражение уровня прав:
В примере мы назначили максимальный уровень доступа всем категориям пользователей.
Соответственно, для изменения уровня прав отдельной категории пользователей нужно изменить только это числовое значение. Например, запретим исполнение файла для всех пользователей:
А потом вернём, но только пользователю-владельцу:
Бывает, что нам нужно изменить права только на все папки или только на все файлы в определённой директории. Часто с этим можно столкнуться при настройке прав на файлы сайтов. Вот вам пара однострочников на этот случай:
Смена прав на 755 для всех папок внутри /var/www/sites/example.com :
Смена прав на 644 для всех файлов внутри /var/www/sites/example.com :
Изменение атрибутов файлов
Помимо прав доступа и владельца каждый файл может иметь ряд атрибутов, определяемых на уровне файловой системы. Атрибуты показывают, какие операции могут или не могут проводиться с файлом в принципе, независимо от того, кто им владеет.
Посмотреть атрибуты файлов в текущей директории можно с помощью команды lsattr . Если запустить её без аргументов, она выведет атрибуты всех файлов в текущей директории. Если указать путь к файлу или папке, она перечислит свойства указанного файла или списка файлов в указанной папке соответственно:
Первые 20 символов в строке предназначены для отображения атрибутов файла.
Список атрибутов может отличаться в зависимости от файловой системы. Вот список основных:
«godmode» — файл становится неуязвим для любых изменений. Его нельзя удалить, переименовать, изменить содержимое, создать символьную ссылку на него.
в файл с таким атрибутом можно только добавлять новые данные. Старое содержимое изменить или удалить не получится. Это пригодится для защиты от вредоносных вставок или замен в файлах, куда постоянно записываются данные — например, в логах. Доступ к изменению старого содержимого по умолчанию есть только у суперпользователя root .
активирует безвозвратное удаление файла. В том смысле, что после удаления файл нельзя будет восстановить с носителя — при удалении все использовавшиеся для хранения файла блоки на диске перезаписываются нулями.
активирует «обратимое» удаление файлов. Это значит, что при удалении файла с этим атрибутом его содержимое можно восстановить.
сжатый файл. Все данные, записываемые в файл, автоматически сжимаются, а данные, извлекаемые из файла — возвращаются в исходное состояние.
настраивает для файла исключение при использовании утилиты dump . То есть файл не будет включен в архив при создании резервной копии этим способом.
показывает, что файл в качестве указателей использует экстенты.
в журналируемых файловых системах ( ext3 , ext4 ) указывает на то, что при сохранении файла он сначала будет записан в журнал ФС, и только потом — на диск.
указывает, что при работе с файлом система не будет обновлять информацию о времени доступа к нему.
атрибут для директорий. Указывает, что все изменения в папке синхронно записываются на диск, минуя кэш.
указывает, что все изменения в файле с этим атрибутом записываются синхронно на диск, минуя кэш.
Изменить атрибуты файла позволяет команда chattr :
То есть, если нам нужно защитить какой-то важный файл от посягательств, можно использовать такую команду:
Проверяем — посягательства не работают.
Если же нам нужно вернуть файл в нормальное состояние, нужно выполнить обратную операцию:
Для просмотра более подробной информации о файловых атрибутах, их ограничениях и правилах применения используйте команду:
FilePermissions
In Linux and Unix, everything is a file. Directories are files, files are files and devices are files. Devices are usually referred to as a node; however, they are still files. All of the files on a system have permissions that allow or prevent others from viewing, modifying or executing. If the file is of type Directory then it restricts different actions than files and device nodes. The super user "root" has the ability to access any file on the system. Each file has access restrictions with permissions, user restrictions with owner/group association. Permissions are referred to as bits.
To change or edit files that are owned by root, sudo must be used — please see RootSudo for details.
If the owner read & execute bit are on, then the permissions are:
There are three types of access restrictions:
There are also three types of user restrictions:
Note: The restriction type scope is not inheritable: the file owner will be unaffected by restrictions set for his group or everybody else.
Folder/Directory Permissions
Directories have directory permissions. The directory permissions restrict different actions than with files or device nodes.
Folders (directories) must have ‘execute’ permissions set (x or 1), or folders (directories) will NOT FUNCTION as folders (directories) and WILL DISAPPEAR from view in the file browser (Nautilus).
Permissions in Action
Using the example above we have the file "/etc/hosts" which is owned by the user root and belongs to the root group.
What are the permissions from the above /etc/hosts ls output?
Changing Permissions
The command to use when modifying permissions is chmod. There are two ways to modify permissions, with numbers or with letters. Using letters is easier to understand for most people. When modifying permissions be careful not to create security problems. Some files are configured to have very restrictive permissions to prevent unauthorized access. For example, the /etc/shadow file (file that stores all local user passwords) does not have permissions for regular users to read or otherwise access.
chmod with Letters
Here are a few examples of chmod usage with letters (try these out on your system).
First create some empty files:
Add owner execute bit:
Add other write & execute bit:
Remove group read bit:
Add read, write and execute to everyone:
chmod with Numbers
Owner, Group and Other is represented by three numbers. To get the value for the options determine the type of access needed for the file then add.
For example if you want a file that has -rw-rw-rwx permissions you will use the following:
Another example if you want a file that has —w-r-x—x permissions you will use the following:
Here are a few examples of chmod usage with numbers (try these out on your system).
First create some empty files:
Add owner execute bit:
Add other write & execute bit:
Remove group read bit:
Add read, write and execute to everyone:
chmod with sudo
Changing permissions on files that you do not have ownership of: (Note that changing permissions the wrong way on the wrong files can quickly mess up your system a great deal! Please be careful when using sudo!)
Recursive Permission Changes
To change the permissions of multiple files and directories with one command. Please note the warning in the chmod with sudo section and the Warning with Recursive chmod section.
Recursive chmod with -R and sudo
To change all the permissions of each file and folder under a specified directory at once, use sudo chmod with -R
Recursive chmod using find, pipemill, and sudo
To assign reasonably secure permissions to files and folders/directories, it’s common to give files a permission of 644, and directories a 755 permission, since chmod -R assigns to both. Use sudo, the find command, and a pipemill to chmod as in the following examples.
To change permission of only files under a specified directory.
To change permission of only directories under a specified directory (including that directory):
Warning with Recursive chmod
WARNING: Although it’s been said, it’s worth mentioning in context of a gotcha typo. Please note, Recursively deleting or chown-ing files are extremely dangerous. You will not be the first, nor the last, person to add one too many spaces into the command. This example will hose your system:
Note the space between the first / and home.
You have been warned.
Changing the File Owner and Group
A file’s owner can be changed using the chown command. For example, to change the foobar file’s owner to tux:
To change the foobar file’s group to penguins, you could use either chgrp or chown with special syntax:
Finally, to change the foobar file’s owner to tux and the group to penguins with a single command, the syntax would be:
Note that, by default, you must use sudo to change a file’s owner or group.
Volume Permissions with umask
This section has been moved to: Fstab#Options
ACL (Access Control List)
Posix ACLs are a way of achieving a finer granularity of permissions than is possible with the standard Unix file permissions. See the full page on ACLs FilePermissionsACLs
Setting up ACL
- Install the acl package:
- Remount partition(s) on which you want to enable ACL. For example:
The commands, setfacl and getfacl, set and read ACLs on files and directories.
Example Usage
- Create a directory with full permission:
GUI ACL Editor
The Eiciel
package allows GUI access to ACLs through the Nautilus file manager.Useful ACL Resources
File removal
To remove a file you cannot delete use
where filename is the name and path of the file to delete.
Nota bene: Be very careful when using the command rm with the -rf option since -r makes the file removal recursive (meaning it will remove files inside of folders) and -f will force the removal even for files which aren’t writable. To play it safe, please consider typing in the absolute path to the file
to prevent any mishaps that can/will occur. It takes longer to type but you can’t put a price on peace of mind. See the rm man page for details.
Sticky Bit
The sticky bit applies only to directories, and is typically used on publicly-writeable directories. Within a directory upon which the sticky bit is applied, users are prevented from deleting or renaming any files that they do not personally own.
To add or remove the sticky bit, use chmod with the "t" flag:
The status of the sticky bit is shown in the other execute field, when viewing the long output of ls. "t" or "T" in the other execute field indicates the sticky bit is set, anything else indicates it is not.
Making a public directory:
Adding the sticky bit (note the "t" in the other execute field):