chgrp
-
This function’s solution assumes a Unix-like operating system.
The
chgrpfunction in PHP will change the group of a file to a different group ID, assuming the PHP process has sufficient privileges to do so.PHP
chgrp('/path/to/foobar', 501);
Ruby’s
File.chownclass method is used to accomplish the same task.Ruby
File.chown(nil, 501, '/path/to/foobar')
The first argument of
File.chownis the user, the second is the group, and the third is the file. Above, the user is set tonil. This will leave the user unchanged.Changing the Group by Name
One nice feature of PHP’s
chownis that the$groupargument is mixed. It can accept either a group ID or a group name.PHP
chown('/path/to/foobar', 'herbert');
File.chownfrom Ruby is not as flexible. It only accepts numeric IDs. To change the group by name, we must first perform a lookup to get the group ID from the name.The
Etcmodule from the Ruby Standard Library contains a methodgetgrnamthat returns aStructof information about a group by name, which includes the group ID. We can use this lookup the group ID and then pass it toFile.chown.Ruby
require 'etc' gid = Etc.getgrnam('herbert').gid File.chown(nil, gid, '/path/to/foobar')
Changing the Group with FileUtils
An alternative to using
FileandEtcto change the group of a file is to useFileUtils, also from the Ruby Standard Library.FileUtils.chowncan change the group by either group ID or name.Ruby
require 'fileutils' # equivalent FileUtils.chown(nil, 501, '/path/to/foobar') FileUtils.chown(nil, 'herbert', '/path/to/foobar')
The first argument of
FileUtils.chownis the user, the second is the group, and the third is the file. Above, the user is set tonil. This will leave the user unchanged.Another useful method is
FileUtils.chown_R, whose usage is the same but will recursively change all files in a given path.see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

