Search code examples
bashshellfiletouch

Recursively touch files with file


I have a directory that contains sub-directories and other files and would like to update the date/timestamps recursively with the date/timestamp of another file/directory.

I'm aware that:

touch -r file directory

changes the date/timestamp for the file or directory with the others, but nothing within it. There's also the find version which is:

find . -exec touch -mt 201309300223.25 {} +\;

which would work fine if i could specify the actual file/directory and use anothers date/timestamp. Is there a simple way to do this? even better, is there a way to avoid changing/updating timestamps when doing a 'cp'?


Solution

  • even better, is there a way to avoid changing/updating timestamps when doing a 'cp'?

    Yes, use cp with the -p option:

    -p

    same as --preserve=mode,ownership,timestamps

    --preserve

    preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all

    Example

    $ ls -ltr
    -rwxrwxr-x 1 me me  368 Apr 24 10:50 old_file
    $ cp old_file not_maintains    <----- does not preserve time
    $ cp -p old_file do_maintains  <----- does preserve time
    $ ls -ltr
    total 28
    -rwxrwxr-x 1 me me  368 Apr 24 10:50 old_file
    -rwxrwxr-x 1 me me  368 Apr 24 10:50 do_maintains   <----- does preserve time
    -rwxrwxr-x 1 me me  368 Sep 30 11:33 not_maintains  <----- does not preserve time
    

    To recursively touch files on a directory based on the symmetric file on another path, you can try something like the following:

    find /your/path/ -exec touch -r $(echo {} | sed "s#/your/path#/your/original/path#g") {} \;
    

    It is not working for me, but I guess it is a matter of try/test a little bit more.