Linux使用touch批量修改文件/文件夹时间戳(含change time)

Linux下touch是一个非常有用的命令。

touch语法结构如下:

touch [-acfm][-d <日期时间>][-r <参考文件或目录>][-t <日期时间>][--help]   [--version][文件或目录...] 或 touch [-acfm][--help][--version][日期时间][文件或目录...]

Usage: touch [OPTION]... FILE...
Mandatory arguments to long options are mandatory for short options too.
  -a    change only the access time
  -d, --date=STRING    parse STRING and use it instead of current time
  -m    change only the modification time
  -r, --reference=FILE    use this file's times instead of current time
  -t STAMP    use [[CC]YY]MMDDhhmm[.ss] instead of current time
  --time=WORD    change the specified time:
          WORD is access, atime, or use: equivalent to -a
          WORD is modify or mtime: equivalent to -m
Note that the -d and -t options accept different time-date formats.

使用举例

--------------------------------------------

touch -m -d "2016-05-20 14:25:50" file
touch -d "2016-05-20 14:25:50" file
touch -d "2016-05-20" file
touch -d "14:25:50" file
或者
touch -t 201605201315.50 file
touch -t 05201315 file

命令参数:

-d使用指定的日期时间。
-a只更改存取时间access
-m只更改变动时间modify

设置日期(设置当前时间,只有root权限才能设置,其他只能查看):

#date //显示当前日期
#date -s 20061010 //设置成20061010,这样会把具体时间设置成空00:00:00
#date -s 12:23:23 //设置具体时间,不会对日期做更改
#date -s "2006-10-10 12:12:23" //这样可以设置全部时间

--------------------------------------------

具体步骤

1、设置系统时间(能影响change time)

date -s "2010-10-10 10:10:10"

2、修改文件时间

#当前目录下文件/文件夹(不能递归):

touch -m -d "2010-10-10 10:10:10" *

#递归修改当前目录下所有文件/文件夹3个时间戳(Access、Modify、Change time):

find ./ * -exec touch {} \;

#递归修改当前目录下所有文件/文件夹指定时间戳(Modify、Change time):

find ./ * -exec touch -m -d "2010-10-10 10:10:10" {} \;

3、还原系统时间

clock --hctosys

请注意:

1、文件的Access time会随着每次访问而更新时间,所有这个参数意义不大,浏览器每打开一次这个文件,Access time均会更新。

2、Change time不能随便修改,必须先修改系统时间才能改变这个值。

查看系统硬件时钟

clock --show

硬件时钟与系统时钟同步:

clock --hctosys  hc代表硬件时间,sys代表系统时间

PS:补充下查看文件时间:

stat file

时间显示示例:

Access: 2010-05-02 01:22:11.000000000 +0800
Modify: 2010-05-02 01:22:11.000000000 +0800
Change: 2010-10-10 00:00:14.000000000 +0800

(文/飘易)

本文来源:http://www.piaoyi.org/linux/Linux-touch-changetime.html


如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。