How to preserve or change the modification time of a file

Commands tested with CentOS!


1. Solution

Save existing modification date:

# MODDATE=`stat -c %y <FILE_NAME>`
# <perform file manipulations>

Reset modification date:

# touch --date="${MODDATE}" <FILE_NAME>

2. Solution

Copy file with preserve mode:

# cp -p <FILE_NAME> <FILE_COPY>
# <perform file manipulations>

Reset modification date:

# touch --reference <FILE_COPY> <FILE_NAME>

Other modification options with command "touch":

Set modification time to the current time:

# touch -m <FILE_NAME>

Set modification time to custom time (24. December 1999, 10:45:30):

# touch -m  -t 199912241045.30 <FILE_NAME>

Set modification and access time (24. December 1999, 10:45:30):

# touch -t 199912241045.30 <FILE_NAME>

The following syntax is used with -t:

[[cc]yy]mmddHHMM[.SS]

[[cc]yy] : year (default is the current year,
           if [yy] is used, but not [cc]:
           if [yy] is between 69 and 99, the value of [cc] is set to 19.
           Otherwise, the value of [cc] is 20)
mm       : month (1 to 12)
dd       : day (1 to 31)
HH       : hour (0 to 23)
MM       : minute (0 to 59)
[.SS]    : second (0 to 60, leap second permitted, default = 0)