- Команда chown Linux
- Команда chown Linux
- 1. Синтаксис и опции
- 2. Использование chown
- Выводы
- How to change owner of folder to current user recursively?
- 3 Answers 3
- Explanation:
- Chown Command: Change Owner of File in Linux
- Linux Chown Command Syntax
- How to Check Ownership of a File in Linux
- How to Change the Owner of a File
- Change the Owner of a File With UID
- Change Ownership of Multiple Linux Files
- How to Change the Group of a File
- Change the Group of a File Using GID
- Change Owner and the Group
- Change Group to a Users Login Group
- Transfer Ownership and Group Settings from One File to Another
- Check Owner and Group Before Making Changes
- Check Owner Only
- Check Group Only
- How to Recursively Change File Ownership
- Chown Command and Symbolic Links
- Display Chown Command Process Details
- Suppress Chown Command Errors
Команда chown Linux
Основа философии Linux — все объекты операционной системы — это файлы, для предоставления доступа к тем или иным возможностям системы мы просто даем доступ пользователю к нужным файлам или убираем. Я более подробно рассказывал обо всех правах в статье права доступа к файлам в Linux, здесь же скажу только что у каждого файла есть три группы прав: для владельца, группы и всех остальных.
При создании файла ему тот пользователь, от имени которого он был создан становится его владельцем, а группой устанавливается основная группа владельца. Но владельца файла и группу можно менять, для этого используются команды chown и chgrp. В этой статье будет рассмотрена команда chown linux, а также основные примеры её использования.
Команда chown Linux
1. Синтаксис и опции
Синтаксис chown, как и других подобных команд linux очень прост:
$ chown пользователь опции /путь/к/файлу
В поле пользователь надо указать пользователя, которому мы хотим передать файл. Также можно указать через двоеточие группу, например, пользователь:группа. Тогда изменится не только пользователь, но и группа. Вот основные опции, которые могут вам понадобиться:
- -c, —changes — подробный вывод всех выполняемых изменений;
- -f, —silent, —quiet — минимум информации, скрыть сообщения об ошибках;
- —dereference — изменять права для файла к которому ведет символическая ссылка вместо самой ссылки (поведение по умолчанию);
- -h, —no-dereference — изменять права символических ссылок и не трогать файлы, к которым они ведут;
- —from — изменять пользователя только для тех файлов, владельцем которых является указанный пользователь и группа;
- -R, —recursive — рекурсивная обработка всех подкаталогов;
- -H — если передана символическая ссылка на директорию — перейти по ней;
- -L — переходить по всем символическим ссылкам на директории;
- -P — не переходить по символическим ссылкам на директории (по умолчанию).
Утилита имеет ещё несколько опций, но это самые основные и то большинство из них вам не понадобится. А теперь давайте посмотрим как пользоваться chown.
2. Использование chown
Например, у нас есть несколько папок dir и их владелец пользователь sergiy:
Давайте изменим владельца папки dir1 на root:
Если вы хотите поменять сразу владельца и группу каталога или файла запишите их через двоеточие, например, изменим пользователя и группу для каталога dir2 на root:
Если вы хотите чтобы изменения применялись не только к этому каталогу, но и ко всем его подкаталогам, добавьте опцию -R:
Дальше давайте изменим группу и владельца на www-data только для тех каталогов и файлов, у которых владелец и группа root в каталоге /dir3:
chown —from=root:root www-data:www-data -cR ./
Для обращения к текущему каталогу используйте путь ./. Мы его использовали и выше. Далее указываем нужную группу с помощью опции —from и просим утилиту выводить изменения, которые она делает в файловой системе с помощью опции -c.
Выводы
Команда chown очень простая и позволяет только менять владельца и группу. Если вы хотите более подробно настроить права для владельца, группы и всех остальных, вам понадобится команда chmod. Права — довольно частая проблема при настройке работы различных программ, знание двух этих команд плюс ls и namei может помочь исправить много ошибок.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
How to change owner of folder to current user recursively?
Using sudo nautilus I created some folders and I want to get rid of root permission on them. But I have many and I want to do it to a entire directory and its containing folders. So how to allow read/write to current user to all files and folders inside a specific directory that is inside /home ?
3 Answers 3
To revert damage done using sudo nautilus you should make yourself the owner of any directories (and their contents) that are owned by root.
You can use find to do this, as it has a test to find only files owned by a specific user.
This will find all the directories in your home owned by root:
sudo find ~ -type d -user root
You can then repeat the find command and add the action you want to do — recursively changing ownership of all the found directories and their contents to the current user:
sudo find ~ -type d -user root -exec sudo chown -R $USER: <> +
Explanation:
- ~ the home directory
- -type d find only directories
- -user root find only stuff belonging to root
- -exec do the following command on whatever was found
- sudo chown -R recursively change owner
- $USER the current user
- : also change group to the specific user
More efficiently, you could omit the -type d to find files of any type belonging to root, and also omit the -R as find will do the recursion for you by acting on all the files
sudo find ~ -user root -exec sudo chown $USER: <> +
Chown Command: Change Owner of File in Linux
The chown command changes user ownership of a file, directory, or link in Linux. Every file is associated with an owning user or group. It is critical to configure file and folder permissions properly.
In this tutorial, learn how to use the Linux chown command with examples provided.
- Linux or UNIX-like system
- Access to a terminal/command line
- A user with sudo privileges to change the ownership. Remember to run the commands with sudo to execute them properly.
Linux Chown Command Syntax
The basic chown command syntax consists of a few segments. The help file shows the following format:
chown [OPTIONS] USER[:GROUP] FILE(s)
- [OPTIONS] – the command can be used with or without additional options.
- [USER] – the username or the numeric user ID of the new owner of a file.
- [:] – use the colon when changing a group of a file.
- [GROUP] – changing the group ownership of a file is optional.
- FILE – the target file.
Superuser permissions are necessary to execute the chown command.
In this guide, we tested the command examples with the chown version 8.28 in Ubuntu 18.04.2 LTS.
To check the chown version on your machine, enter:
The output will look similar to this:
How to Check Ownership of a File in Linux
First, you need to know the original file owner or group before making ownership changes using the chown command.
To check the group or ownership of Linux files and directories in the current location, run the following command:
An example output of the ls command looks like this:
How to Change the Owner of a File
Changing the owner of a file with chown requires you to specify the new owner and the file. The format of the command is:
The following command changes the ownership of a file sample from root to the user test:
Use the same format to change the ownership for both files and directories.
Change the Owner of a File With UID
Instead of a username, you can specify a user ID to change the ownership of a file.
Make sure there is no user with the same name as the numeric UID. If there is, the chown command gives priority to the username, not the UID.
Note: To check a user’s ID, run id -u USERNAME from the terminal.
Change Ownership of Multiple Linux Files
List the target file names after the new user to change the ownership for multiple files. Use single spaces between the file names.
In the following example, root will be the new owner of files sample2 and sample3.
chown root sample2 sample3
Combine file names and directory names to change their ownership with one command. For example:
Do not forget that the commands are case sensitive.
How to Change the Group of a File
With chown, you can change a group for a file or directory without changing the owning user. The result is the same as using the chgrp command.
Run the chown command using the colon and a group name:
The following example changes the group of the file sample3 from grouptest to group3.
List multiple names of files or directories to make bulk changes.
Change the Group of a File Using GID
Similar to UID, use a group ID (GID) instead of a group name to change the group of a file.
Change Owner and the Group
To assign a new owner of a file and change its group at the same time, run the chown command in this format:
chown NewUser:NewGroup FILE
Therefore, to set linuxuser as the new owner and group2 as the new group of the file sample2:
chown linuxuser:group3 sample3
Remember that there are no spaces before or after the colon.
Change Group to a Users Login Group
The chown command assigns the owner’s login group to the file when no group is specified.
To do so, define a new user followed by a colon, space, and the target file:
The following example changes the group ownership to the login group of linuxuser:
Transfer Ownership and Group Settings from One File to Another
Rather than changing the ownership to a specific user, you can use the owner and a group of a reference file.
Add the —reference option to the chown command to copy the settings from one file to another:
chown --reference=ReferenceFILE FILE
Remember to type in the names of the files correctly to avoid the error message:
Check Owner and Group Before Making Changes
The chown command —from option lets you verify the current owner and group and then apply changes.
The chown syntax for checking both the user and group looks like this:
chown --from=CurrentUser:CurrentGroup NewUser:NewGroup FILE
The example below shows we first verified the ownership and the group of the file sample3:
chown --from=root:group2 linuxuser:group3 sample3
Then chown changed the owner to linuxuser and the group to group3.
Check Owner Only
The option —from can be used to validate only the current user of a file.
chown --from=CurrentUser NewUser FILE
chown --from=root linuxuser sample3
Check Group Only
Similar to the previous section, you can validate only the group of a file using the option —from .
chown --from=:CurrentGroup :NewGroup FILE
Here is an example where we verified the current group before changing it:
chown --from=:group3 :group4 FILE
Remember to use the colon for both group names to avoid error messages.
How to Recursively Change File Ownership
The chown command allows changing the ownership of all files and subdirectories within a specified directory. Add the -R option to the command to do so:
chown -R NewUser:NewGroup DirNameOrPath
In the following example, we will recursively change the owner and the group for all files and directories in Dir1.
chown -R linuxuser:group3 Dir1
Chown Command and Symbolic Links
To change the owner of a symbolic link, use the -h option. Otherwise, the ownership of the linked file will be changed.
The following image shows how symbolic links behave when -h is omitted.
The owner and group of the symbolic link remain intact. Instead, the owner and the group of the file textfile changed.
To push the changes to the link, run the chown command with the -h flag:
chown -h NewUser:NewGroup SymbolicLink
In the following example, we changed the owner and group of a symbolic link.
Display Chown Command Process Details
By default, the terminal does not display the chown process information. To see what happens under the hood, use one of the two command line flags:
- The option –v produces the process details even when the ownership stays the same.
- The option –c displays the output information only when an owner or group of the target file changes.
For example, if we specify the current owner as a new owner of the file:
chown -v linuxuser sample2
The terminal produces the following output:
Switch from -v to -c and there will be no messages in this case. This happens because there are no owner or group changes.
The information is particularly useful with the recursive chown command:
In this example, the output lists all objects affected after running the command.
Suppress Chown Command Errors
To avoid seeing potential error messages when running the chown command, use the -f option:
The example below shows the error message for a non-existent file or directory:
Adding the -f flag suppresses most error messages. However, if you specify an invalid username, the error message appears:
Now you know how to use chown command in Linux to change a file’s user and/or group ownership.
Take extra caution when changing the group or ownership of a file or directories.