17

I know how to get a file's mtime in epoch format:

stat --format=%Y <file>

But I have not been able to figure out how to set a file's mtime in epoch format. The touch(1) man page appears to only accept a "timestamp" value (more-or-less fixed format which uses months, days, hours, minues, etc) or a "mostly free format human readable date string".

Is there another utility I should be looking into?

Thanks.

terdon
  • 234,489
  • 66
  • 447
  • 667
eil
  • 363
  • 1
  • 3
  • 9
  • 1
    Please *always* include your OS. Solutions very often depend on the Operating System being used. Are you using Unix, Linux, BSD, OSX, something else? Which version? – terdon Jun 28 '14 at 15:56

3 Answers3

16

At least in the GNU world:

touch --date=@1403970787 file

Like with date.

Hauke Laging
  • 88,146
  • 18
  • 125
  • 174
2

With the touch command from GNU coreutils (i.e. on non-embedded Linux and Cygwin), look at the full manual (usually available locally in info format) for the documentation of date input formats. Epoch dates are indicated with the prefix @:

touch -d @1234567890 foo

This also works with BusyBox (at least on some systems, it might depend on compilation options).

With *BSD, I don't think you can do this with touch alone, but you can call date to format the epoch time into a format that touch accepts.

touch -d "$(date -r 1234567890 +%Y%m%d%H%M.%S)" foo

POSIX notoriously lacks ways to manipulate epoch dates. You can use perl.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
1

With perl:

$ perl -e 'utime (stat($_))[8], time(), $_ for @ARGV' file1 file2 ...

This will change mtime of all files in @ARGV. (stat($_))[8] is atime of file.

utime can receive list of files, if you don't care about changing atime, you can try:

 $ perl -e '$t = time(); utime $t, $t, @ARGV' file1 file2 ...

Note

utime depends on C runtime library and filesystem is using. see more in perldoc -f utime and perldoc perlport.

cuonglm
  • 150,973
  • 38
  • 327
  • 406