Method: FileUtils.copy

Defined in:
lib/fileutils.rb

.copyObject

Copies files.

Arguments src (a single path or an array of paths) and dest (a single path) should be interpretable as paths.

If src is the path to a file and dest is not the path to a directory, copies src to dest:

FileUtils.touch('src0.txt')
File.exist?('dest0.txt') # => false
FileUtils.cp('src0.txt', 'dest0.txt')
File.file?('dest0.txt')  # => true

If src is the path to a file and dest is the path to a directory, copies src to dest/src:

FileUtils.touch('src1.txt')
FileUtils.mkdir('dest1')
FileUtils.cp('src1.txt', 'dest1')
File.file?('dest1/src1.txt') # => true

If src is an array of paths to files and dest is the path to a directory, copies from each src to dest:

src_file_paths = ['src2.txt', 'src2.dat']
FileUtils.touch(src_file_paths)
FileUtils.mkdir('dest2')
FileUtils.cp(src_file_paths, 'dest2')
File.file?('dest2/src2.txt') # => true
File.file?('dest2/src2.dat') # => true

Keyword arguments:

  • preserve: true - preserves file times.

  • noop: true - does not copy files.

  • verbose: true - prints an equivalent command:

    FileUtils.cp('src0.txt', 'dest0.txt', noop: true, verbose: true)
    FileUtils.cp('src1.txt', 'dest1', noop: true, verbose: true)
    FileUtils.cp(src_file_paths, 'dest2', noop: true, verbose: true)
    

    Output:

    cp src0.txt dest0.txt
    cp src1.txt dest1
    cp src2.txt src2.dat dest2
    

Raises an exception if src is a directory.

Related: methods for copying.


883
884
885
886
887
888
889
# File 'lib/fileutils.rb', line 883

def cp(src, dest, preserve: nil, noop: nil, verbose: nil)
  fu_output_message "cp#{preserve ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if verbose
  return if noop
  fu_each_src_dest(src, dest) do |s, d|
    copy_file s, d, preserve
  end
end