Method: FileUtils.chown

Defined in:
lib/fileutils.rb

.chown(user, group, list, noop: nil, verbose: nil) ⇒ Object

Changes the owner and group on the entries at the paths given in list (a single path or an array of paths) to the given user and group; returns list if it is an array, [list] otherwise:

  • Modifies each entry that is a regular file using File.chown.

  • Modifies each entry that is a symbolic link using File.lchown.

Argument list or its elements should be interpretable as paths.

User and group:

  • Argument user may be a user name or a user id; if nil or -1, the user is not changed.

  • Argument group may be a group name or a group id; if nil or -1, the group is not changed.

  • The user must be a member of the group.

Examples:

# One path.
# User and group as string names.
File.stat('src0.txt').uid # => 1004
File.stat('src0.txt').gid # => 1004
FileUtils.chown('user2', 'group1', 'src0.txt')
File.stat('src0.txt').uid # => 1006
File.stat('src0.txt').gid # => 1005

# User and group as uid and gid.
FileUtils.chown(1004, 1004, 'src0.txt')
File.stat('src0.txt').uid # => 1004
File.stat('src0.txt').gid # => 1004

# Array of paths.
FileUtils.chown(1006, 1005, ['src0.txt', 'src0.dat'])

# Directory (not recursive).
FileUtils.chown('user2', 'group1', '.')

Keyword arguments:

  • noop: true - does not change permissions; returns nil.

  • verbose: true - prints an equivalent command:

    FileUtils.chown('user2', 'group1', 'src0.txt', noop: true, verbose: true)
    FileUtils.chown(1004, 1004, 'src0.txt', noop: true, verbose: true)
    FileUtils.chown(1006, 1005, ['src0.txt', 'src0.dat'], noop: true, verbose: true)
    FileUtils.chown('user2', 'group1', path, noop: true, verbose: true)
    FileUtils.chown('user2', 'group1', '.', noop: true, verbose: true)
    

    Output:

    chown user2:group1 src0.txt
    chown 1004:1004 src0.txt
    chown 1006:1005 src0.txt src0.dat
    chown user2:group1 src0.txt
    chown user2:group1 .
    

Related: FileUtils.chown_R.


1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
# File 'lib/fileutils.rb', line 1897

def chown(user, group, list, noop: nil, verbose: nil)
  list = fu_list(list)
  fu_output_message sprintf('chown %s %s',
                            (group ? "#{user}:#{group}" : user || ':'),
                            list.join(' ')) if verbose
  return if noop
  uid = fu_get_uid(user)
  gid = fu_get_gid(group)
  list.each do |path|
    Entry_.new(path).chown uid, gid
  end
end