如何更改目录以及该目录中所有子文件夹的时间戳以反映所包含文件的修改时间?
\n\n例如,使用以下目录结构:
\n\n[Jan 9] root\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 3] file1\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 7] file2\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 6] sub1\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 2] file3\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [Jan 1] file4\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [Jan 4] sub2\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [Jan 8] file5\n
Run Code Online (Sandbox Code Playgroud)\n\n这是生成该内容的单行代码:
\n\nmkdir -p root/sub1 root/sub2 && touch -d '2018-01-08' root/sub2/file5 && touch -d '2018-01-04' root/sub2/ && touch -d '2018-01-01' root/sub1/file4 && touch -d '2018-01-02' root/sub1/file3 && touch -d '2018-01-06' root/sub1/ && touch -d '2018-01-07' root/file2 && touch -d '2018-01-03' root/file1 && touch -d '2018-01-09' root/\n
Run Code Online (Sandbox Code Playgroud)\n\n它可以列出tree -D
我想将三个目录的时间戳更改为:
\n\n[Jan 8] root\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 3] file1\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 7] file2\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 2] sub1\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [Jan 2] file3\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [Jan 1] file4\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [Jan 8] sub2\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [Jan 8] file5\n
Run Code Online (Sandbox Code Playgroud)\n\n笔记:
\n\nThe reason that I'm doing this is for a directory that gets copied with rsync. The directory is checked into git and could get rsynced from any place that has the repository checked out. To ensure that rsync is consistent and idempotent from the various places, I need to ensure that the time stamps and permissions of everything are in a known state. I already have a script that sets the timestamps of files based on when they were committed to git. I also have a script that sets the permissions on all files and directories to a known state. The only portion that I'm struggling with is bubbling time stamps from the files up to parent directories.
\n\nI would like one line or short script that I can run from the command line to set directory timestamps based on the timestamps of their contents.
\nUnless I'm overlooking something (haven't tested this extensively):
find . -depth -type d -execdir \
sh -c 'touch "$PWD/$0" -r "$PWD/$0/$( ls -t "$PWD/$0" | head -n 1 )"' \
{} \;
Run Code Online (Sandbox Code Playgroud)
What it does:
ls -t
, lists their contents in reverse datetime order and gets the firsttouch
to touch the directory using its newest object as timestampFor correct datetime "bubbling", the -depth
option ensures that subdirectories are processed before the current subdirectory ("depth first"). Once the subdirectories have been processed and their datetimes updated, the current directory is processed (and possibly inherits one of the daughter subdirectories' timestamp).