This article introduces how to modify file modification time (mtime) and creation time (ctime) in Bash on the Linux command line.
There are cases where you want to update file modification time without writing to or accessing the file.
That said, it seems you can’t update files with printf or echo, so unless you want to do something troublesome like adding and removing characters, it’s better to use the method explained here.
# A newline is added to the file
echo "" >> "${TIME_MANAGEMENT_DIR}/time_management.txt"
# No changes are made to the file, but the modification time is not changed either.
printf "" >> "${TIME_MANAGEMENT_DIR}/time_management.txt"
First, let’s check the current modification time and access time of a file with stat.
$stat "${TIME_MANAGEMENT_DIR}/time_management.txt"
File: '/mnt/c/time_management/time_management.txt'
Size: 385 Blocks: 0 IO Block: 4096 regular file
Device: 11h/17d Inode: 336362597169482697 Links: 1
Access: (0777/-rwxrwxrwx) Uid: ( 1000/ yuis) Gid: ( 1000/ yuis)
Access: 2019-06-29 14:59:40.666044600 +0900
Modify: 2019-06-29 14:59:40.666044600 +0900
Change: 2019-06-29 14:59:40.666044600 +0900
To change the access time, use touch -a.
$ /bin/touch -a --date="@1561788231" "${TIME_MANAGEMENT_DIR}/time_management.txt"
# // `1561788231` ... `date +%s`
$ /bin/touch --help
-a change only the access time
-d, --date=STRING parse STRING and use it instead of current time
-m change only the modification time
It changed.
$ stat "${TIME_MANAGEMENT_DIR}/time_management.txt"
File: '/mnt/c/time_management/time_management.txt'
Size: 385 Blocks: 0 IO Block: 4096 regular file
Device: 11h/17d Inode: 336362597169482697 Links: 1
Access: (0777/-rwxrwxrwx) Uid: ( 1000/ yuis) Gid: ( 1000/ yuis)
Access: 2019-06-29 15:03:51.000000000 +0900
Modify: 2019-06-29 14:59:40.666044600 +0900
Change: 2019-06-29 15:04:49.266605100 +0900
Birth: -
Similarly to the above, use touch -m for modification time.
/bin/touch -m --date="@$( date +%s )" "${TIME_MANAGEMENT_DIR}/time_management.txt"
Linux - Fake File Access, Modify and Change TimeStamps - ShellHacks