Method: FileUtils.ln

Defined in:
lib/fileutils.rb

.ln(src, dest, force: nil, noop: nil, verbose: nil) ⇒ Object

Creates hard links.

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

When src is the path to an existing file and dest is the path to a non-existent file, creates a hard link at dest pointing to src; returns zero:

Dir.children('tmp0/')                    # => ["t.txt"]
Dir.children('tmp1/')                    # => []
FileUtils.ln('tmp0/t.txt', 'tmp1/t.lnk') # => 0
Dir.children('tmp1/')                    # => ["t.lnk"]

When src is the path to an existing file and dest is the path to an existing directory, creates a hard link at dest/src pointing to src; returns zero:

Dir.children('tmp2')               # => ["t.dat"]
Dir.children('tmp3')               # => []
FileUtils.ln('tmp2/t.dat', 'tmp3') # => 0
Dir.children('tmp3')               # => ["t.dat"]

When src is an array of paths to existing files and dest is the path to an existing directory, then for each path target in src, creates a hard link at dest/target pointing to target; returns src:

Dir.children('tmp4/')                               # => []
FileUtils.ln(['tmp0/t.txt', 'tmp2/t.dat'], 'tmp4/') # => ["tmp0/t.txt", "tmp2/t.dat"]
Dir.children('tmp4/')                               # => ["t.dat", "t.txt"]

Keyword arguments:

  • force: true - overwrites dest if it exists.

  • noop: true - does not create links.

  • verbose: true - prints an equivalent command:

    FileUtils.ln('tmp0/t.txt', 'tmp1/t.lnk', verbose: true)
    FileUtils.ln('tmp2/t.dat', 'tmp3', verbose: true)
    FileUtils.ln(['tmp0/t.txt', 'tmp2/t.dat'], 'tmp4/', verbose: true)
    

    Output:

    ln tmp0/t.txt tmp1/t.lnk
    ln tmp2/t.dat tmp3
    ln tmp0/t.txt tmp2/t.dat tmp4/
    

Raises an exception if dest is the path to an existing file and keyword argument force is not true.

Related: FileUtils.link_entry (has different options).


517
518
519
520
521
522
523
524
# File 'lib/fileutils.rb', line 517

def ln(src, dest, force: nil, noop: nil, verbose: nil)
  fu_output_message "ln#{force ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if verbose
  return if noop
  fu_each_src_dest0(src, dest) do |s,d|
    remove_file d, true if force
    File.link s, d
  end
end