In Linux, each file is associated with an owner and a group and has permissions that determine which users may read, write, or execute the file.
This article explains how to use the chgrp
command to change the group ownership of given files.
chgrp
Command SyntaxThe chgrp
command takes the following form:
chgrp [OPTIONS] GROUP FILE..
Copy
GROUP
, name of the new group, or the group ID (GID). Numeric GID must be prefixed with the +
symbol.FILE..
, name of one or more files.Unlike the [chown](https://linuxize.com/post/linux-chown-command/)
command that allows you to change the user and group ownership, chgrp
changes only the group ownership.
To find out to which group the file belongs to, use the [ls -l](https://linuxize.com/post/how-to-list-files-in-linux-using-the-ls-command/)
command.
Regular users can change the group of the file only if they own the file and only to a group of which they are a member. Administrative users can change the group ownership of all files.
To change the group ownership of a file or directory invoke the chgrp
command followed by the new group name and the target file as arguments.
For example, to change the group of the file filename
to www-data
you would run:
chgrp www-data filename
If you run the command with an unprivileged user, you will get an “Operation not permitted” error. To suppress the error message, invoke the command with the -f
option. By default, on success, chgrp
doesn’t produce any output and returns zero.
You can also pass multiple files as arguments to the chgrp
command:
chgrp www-data file1 file2 dir1
Use the -v
option to get information about the files that are being processed:
chgrp www-data file1 file2
changed group of 'file1' from nginx to www-data
group of 'file2' retained as www-data
To print information only about those files which group actually changes use -c
instead of -v
.
The numeric group ID (GID) can be used instead of the username. The following example changes the file’s group ownership to a new group with GID of 1000:
chgrp +1000 filename
When not operating recursively, the default behavior of the chgrp
command is to change the group ownership of the symlink targets, not the symbolic links themselves.
For example, if you try to change the group of the symbolic link symlink1
that points to /opt/file1
, chgrp
will change the ownership of the file or directory the symlink points to:
chgrp www-data symlink1
The chances are that instead of changing the target group, you will get a “cannot dereference ‘symlink1’: Permission denied” error.
The error happens because by default on most Linux distributions, symlinks are protected, and you cannot operate on target files. This option is specified in /proc/sys/fs/protected_symlinks
. 1
means enabled and 0
disabled. We recommend not to disable the symlink protection.
To change the group ownership of the symlink itself, use the -h
option:
chgrp -h www-data symlink1
#linux