liveBook · Manning

FileUtils

As explained in The Well-Grounded Rubyist, Fourth Edition

FileUtils is a Ruby standard library module providing high-level operations for manipulating files and directories.

FileUtils is a Ruby standard-library module for concise, high-level file and directory manipulation. Require it with `require 'fileutils'`; its methods use names familiar from system commands such as `cp`, `mv`, `rm`, `mkdir`, and `ln_s`. section 12.5.1 section 1.2.1

Common operations include:

  • Copy one or several files with `FileUtils.cp`, creating a destination directory with `FileUtils.mkdir`. section 12.5.1
  • Move files with `FileUtils.mv`, remove individual files with `FileUtils.rm`, and recursively remove a directory with `FileUtils.rm_rf`. section 12.5.1
  • Create symbolic links with `FileUtils.ln_s` where the operating system supports them; most other methods are portable. section 12.5.1

Preview or suppress a command

`FileUtils::DryRun.rm_rf("backup")` prints `rm -rf backup` without executing it. `FileUtils::NoWrite.rm("backup/super.rb")` performs no deletion, leaving the file available for verification. section 12.5.1

>> require 'fileutils'
=> true   # or 'false', which just means irb already loaded fileutils
>> FileUtils.cp("baker.rb", "baker.rb.bak")
=> nil
>> FileUtils.mkdir("backup")        1
=> ["backup"]
>> FileUtils.cp(["ensure.rb", "super.rb"], "backup")
=> ["ensure.rb", "super.rb"]
>> Dir["backup/*"]                          2
=> ["backup/ensure.rb", "backup/super.rb"]

A runnable sequence shows requiring FileUtils, creating a backup directory, copying multiple files, and checking the result with `Dir[]`. section 12.5.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Demonstrates common operations, command analogies, portability, and DryRun or NoWrite safeguards without exhaustive API coverage.
Examples
Uses backup creation, multi-file copying, moving, deletion, recursive removal, symbolic linking, directory listing, and existence checks.
What it assumes
Assumes Ruby program execution and basic files, directories, and system-command familiarity while showing how to require the library.
What you can do after
Operate/configure file maintenance through FileUtils methods and preview or suppress destructive commands before execution.
How it connects
Connects file maintenance with File, IO, Pathname, StringIO, OpenURI, Dir, and operating-system file commands.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.