3

I work on testcase, each of being a subdirectory of ~/test. It's convenient to see which were the testcases I worked most recently using something like ls -rtl. Now I'd like to remove certain temporary files from the test directories; alas, that would change the timestamp of the directories.

Is it possible to remove a file from a directory without changing the directory's modification timestamp?

  • can the temporary files be placed somewhere else? because the filename is part of the directory, not the file itself, so when a filename goes away... – thrig May 22 '18 at 20:20
4

You'll have to reset the timestamp on the directory after removing the files. Assuming GNU tools, something like this should work:

mtime=$(stat -c %y dir)            # get the timestamp, store in $mtime
rm dir/somefile dir/someotherfile  # do whatever you need
touch -d "$mtime" dir              # set the timestamp back

That resets the modification (mtime) and access (atime) timestamps on the directory to the original modification timestamp, but also sets the change timestamp (ctime) to the current time. Changing the ctime is unavoidable, but you probably don't care about it or atime.

1

The touch command provides the -r option which allows you to touch a file with the same timestamps as a reference file. As such, you could do this:

touch -r /dir/somefile /tmp/_thetimestamps  # save the timestamps in /tmp/_thetimestamps
rm /dir/somefile                            # do whatever you need
touch -r /tmp/_thetimestamps /dir           # set the timestamps back

Linux Man:

-r, --reference=FILE
      use this file's times instead of current time

Unix Man:

-r       Use the access and modifications times from the specified file
         instead of the current time of day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.