- How to Change File/Group Owner with chown Command in Linux
- How to view file permissions
- How to change file owner with chown command
- How to change the group owner with chown command
- How to change both file owner and group owner of a file
- How to recursively change file ownership
- How to change ownership using a reference file
- Linux change users file
- NAME
- SYNOPSIS
- DESCRIPTION
- OPTIONS
- EXAMPLES
- AUTHOR
- REPORTING BUGS
- COPYRIGHT
- SEE ALSO
- Команда chown Linux
- Команда chown Linux
- 1. Синтаксис и опции
- 2. Использование chown
- Выводы
How to Change File/Group Owner with chown Command in Linux
Short for change ownership, Chown command is a command-line utility that is used to change the user or group ownership of a file or directory and even links. The Linux philosophy is such that every file or directory is owned by a specific user or group with certain access rights.
Using different examples, we will try and see the various use cases of the chown command . Chown command employs quite a simple and straight forward syntax.
$ chown OPTIONS USER: GROUP file(s)
Let’s briefly flesh out the parameters:
The attribute USER refers to the username of the user that will own the file. You can specify either the username or the UID ( User ID). Meanwhile, the GROUP option indicates the name of the new group that the file will acquire after running the command. The file option represents a regular file or a directory or even a symbolic link. These are the three entities whose permissions can be altered.
A few points to note:
1) When the USER option is specified alone, ownership of the file/directory changes to that of the specified user while the group ownership remains unchanged. Here’s an example:
In the above command, user ownership of the file file1.txt changes from the current user to the user john.
2) If the USER option is proceeded by a full colon i.e. USER: and the group name is not provided, then the user takes ownership of the file but the file’s group ownership switches to the user’s login group. For example:
In this example, the user john takes ownership of the file file1.txt, but the group ownership of the file changes to john’s login group.
3) When both the user and group options are specified separated by a colon i.e USER:GROUP – without any spaces therein – the file takes ownership of the new user and the group as specified
In the above example, the file takes the user and group ownership of user john.
4) When the USER option is left out and instead the group option is preceded by the full colon :GROUP then, only the group ownership of the file changes.
How to view file permissions
To view file permissions, simply use the ls -l command followed by the file name
From the output, we can see that the file is owned by user linuxtechi which and belongs to the group linuxtechi in the 3rd and 4th columns respectively.
How to change file owner with chown command
Before changing permissions, always invoke sudo if you are not working as the root user. This gives you elevated privileges to change user and group ownership of a file.
To change file ownership, use the syntax:
$ sudo chown james file1.txt
From the output, you can clearly see that the ownership of the file has changed from linuxtechi to user james .
Alternatively, instead of using the username, you can pass the UID of the user instead. To get the UID, view the /etc/passwd file.
$ cat /etc/passwd | grep username
From the example below, we can see that the UID of user linuxtechi is 1002
To change the file ownership back to linuxtechi user, we shall execute the command:
How to change the group owner with chown command
As earlier discussed, to change the group owner of a file, omit the user and simply prefix the group name with a full colon.
For example, to change the group owner of file1.txt from linuxtechi to docker , we executed the command:
$ sudo chown :docker file1.txt
How to change both file owner and group owner of a file
If you want to change both the owner and group that a file belongs to, specify both the user and group options separated by a full colon as shown in the syntax below. Be sure that there are no spaces between the options and the colon.
$ sudo chown user:group filename
For example, the following command changes the ownership of the file file1.txt to user james and group redis as verified using the ls command.
$ sudo chown james:redis file1.txt
How to recursively change file ownership
When applying permissions to directories, you might want to apply changes recursively i.e make the ownership changes to descend and apply to files and sub-directories. To achieve this, user the recursive option -R or –recursive directive.
$ sudo chown -R user:group directory
For example, the command below assigns all files and folders in the /var/www directory ownership to the www-data group.
$ sudo chown -R :www-data /var/www
The example below assigns ownership of the directory reports alongside all the files and folders in the directory to the user linuxtechi.
$ sudo chown -R linuxtechi reports
How to change ownership using a reference file
Lastly, there’s a nifty way that you can use to change ownership of a file, and that is by using a reference file. Using the chown command, you can change the user and group ownership of a file using another file as the point of reference.
The syntax is shown below:
$ chown –reference=ref_file file
Suppose you want to assign user and group ownership of file1.txt to another file file2.txt. How would you go about it? This is illustrated in the command below.
$ chown --reference=file1.txt file2.txt
The output above confirms that file2.txt inherits the user and group ownership of file1.txt .In the command, file1.txt is the reference file.
Chown command is a powerful tool that is used for managing file and directory ownership. For additional information, check out the chown man pages.
Linux change users file
NAME
chown - change file owner and group
SYNOPSIS
chown [OPTION]. [OWNER][:[GROUP]] FILE. chown [OPTION]. --reference=RFILE FILE.
DESCRIPTION
This manual page documents the GNU version of chown. chown changes the user and/or group ownership of each given file. If only an owner (a user name or numeric user ID) is given, that user is made the owner of each given file, and the files' group is not changed. If the owner is followed by a colon and a group name (or numeric group ID), with no spaces between them, the group ownership of the files is changed as well. If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group. If the colon and group are given, but the owner is omitted, only the group of the files is changed; in this case, chown performs the same function as chgrp. If only a colon is given, or if the entire operand is empty, neither the owner nor the group is changed.
OPTIONS
Change the owner and/or group of each FILE to OWNER and/or GROUP. With --reference, change the owner and group of each FILE to those of RFILE. -c, --changes like verbose but report only when a change is made -f, --silent, --quiet suppress most error messages -v, --verbose output a diagnostic for every file processed --dereference affect the referent of each symbolic link (this is the default), rather than the symbolic link itself -h, --no-dereference affect symbolic links instead of any referenced file (useful only on systems that can change the ownership of a symlink) --from=CURRENT_OWNER:CURRENT_GROUP change the owner and/or group of each file only if its current owner and/or group match those specified here. Either may be omitted, in which case a match is not required for the omitted attribute --no-preserve-root do not treat '/' specially (the default) --preserve-root fail to operate recursively on '/' --reference=RFILE use RFILE's owner and group rather than specifying OWNER:GROUP values -R, --recursive operate on files and directories recursively The following options modify how a hierarchy is traversed when the -R option is also specified. If more than one is specified, only the final one takes effect. -H if a command line argument is a symbolic link to a directory, traverse it -L traverse every symbolic link to a directory encountered -P do not traverse any symbolic links (default) --help display this help and exit --version output version information and exit Owner is unchanged if missing. Group is unchanged if missing, but changed to login group if implied by a ':' following a symbolic OWNER. OWNER and GROUP may be numeric as well as symbolic.
EXAMPLES
chown root /u Change the owner of /u to "root". chown root:staff /u Likewise, but also change its group to "staff". chown -hR root /u Change the owner of /u and subfiles to "root".
AUTHOR
Written by David MacKenzie and Jim Meyering.
REPORTING BUGS
Report chown bugs to bug-coreutils@gnu.org GNU coreutils home page: http://www.gnu.org/software/coreutils/> General help using GNU software: http://www.gnu.org/gethelp/> Report chown translation bugs to http://translationproject.org/team/>
COPYRIGHT
Copyright © 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.
SEE ALSO
chown(2) The full documentation for chown is maintained as a Texinfo manual. If the info and chown programs are properly installed at your site, the command info coreutils 'chown invocation' should give you access to the complete manual.
© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.
Команда 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.