Method: FileUtils.touch

Defined in:
lib/fileutils.rb

.touch(list, noop: nil, verbose: nil, mtime: nil, nocreate: nil) ⇒ Object

Updates modification times (mtime) and access times (atime) of the entries given by the paths in list (a single path or an array of paths); returns list if it is an array, [list] otherwise.

By default, creates an empty file for any path to a non-existent entry; use keyword argument nocreate to raise an exception instead.

Argument list or its elements should be interpretable as paths.

Examples:

# Single path.
f = File.new('src0.txt') # Existing file.
f.atime # => 2022-06-10 11:11:21.200277 -0700
f.mtime # => 2022-06-10 11:11:21.200277 -0700
FileUtils.touch('src0.txt')
f = File.new('src0.txt')
f.atime # => 2022-06-11 08:28:09.8185343 -0700
f.mtime # => 2022-06-11 08:28:09.8185343 -0700

# Array of paths.
FileUtils.touch(['src0.txt', 'src0.dat'])

Keyword arguments:

  • mtime: time - sets the entry’s mtime to the given time, instead of the current time.

  • nocreate: true - raises an exception if the entry does not exist.

  • noop: true - does not touch entries; returns nil.

  • verbose: true - prints an equivalent command:

    FileUtils.touch('src0.txt', noop: true, verbose: true)
    FileUtils.touch(['src0.txt', 'src0.dat'], noop: true, verbose: true)
    FileUtils.touch(path, noop: true, verbose: true)
    

    Output:

    touch src0.txt
    touch src0.txt src0.dat
    touch src0.txt
    

Related: FileUtils.uptodate?.


2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
# File 'lib/fileutils.rb', line 2007

def touch(list, noop: nil, verbose: nil, mtime: nil, nocreate: nil)
  list = fu_list(list)
  t = mtime
  if verbose
    fu_output_message "touch #{nocreate ? '-c ' : ''}#{t ? t.strftime('-t %Y%m%d%H%M.%S ') : ''}#{list.join ' '}"
  end
  return if noop
  list.each do |path|
    created = nocreate
    begin
      File.utime(t, t, path)
    rescue Errno::ENOENT
      raise if created
      File.open(path, 'a') {
        ;
      }
      created = true
      retry if t
    end
  end
end