Method: FileUtils.rmdir

Defined in:
lib/fileutils.rb

.rmdir(list, parents: nil, noop: nil, verbose: nil) ⇒ Object

Removes directories at the paths in the given list (a single path or an array of paths); returns list, if it is an array, [list] otherwise.

Argument list or its elements should be interpretable as paths.

With no keyword arguments, removes the directory at each path in list, by calling: Dir.rmdir(path); see Dir.rmdir:

FileUtils.rmdir(%w[tmp0/tmp1 tmp2/tmp3]) # => ["tmp0/tmp1", "tmp2/tmp3"]
FileUtils.rmdir('tmp4/tmp5')             # => ["tmp4/tmp5"]

Keyword arguments:

  • parents: true - removes successive ancestor directories if empty.

  • noop: true - does not remove directories.

  • verbose: true - prints an equivalent command:

    FileUtils.rmdir(%w[tmp0/tmp1 tmp2/tmp3], parents: true, verbose: true)
    FileUtils.rmdir('tmp4/tmp5', parents: true, verbose: true)
    

    Output:

    rmdir -p tmp0/tmp1 tmp2/tmp3
    rmdir -p tmp4/tmp5
    

Raises an exception if a directory does not exist or if for any reason a directory cannot be removed.

Related: methods for deleting.


443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/fileutils.rb', line 443

def rmdir(list, parents: nil, noop: nil, verbose: nil)
  list = fu_list(list)
  fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if verbose
  return if noop
  list.each do |dir|
    Dir.rmdir(dir = remove_trailing_slash(dir))
    if parents
      begin
        until (parent = File.dirname(dir)) == '.' or parent == dir
          dir = parent
          Dir.rmdir(dir)
        end
      rescue Errno::ENOTEMPTY, Errno::EEXIST, Errno::ENOENT
      end
    end
  end
end