Bash to select oldest folder in directory and write to log

In the bash below the oldest folder in a directory is selected. If there are 3 folders in the directory /home/cmccabe/Desktop/NGS/test and nothing is done to them (ie. no files deleted, renamed) then the bash correctly identifies f1 as the oldest. However, if something is done to the folder then the bash identifies f2 as the oldest. I am not sure why or how to prevent that from happening. Thank you :).

folders in directory

f1
f2
f3

Bash

# oldest folder used analysis and version log created 
dir=/home/cmccabe/Desktop/NGS/test 
{ 
read -r -d $'\t' time && read -r -d '' filename
 } < <(find "$dir" -maxdepth 1 -mindepth 1 -printf '%T+\t%P\0' | sort -z ) 
printf "The oldest folder is $filename, created on $time and analysis done using v1.3 by $USER at $(date "+%D %r")\n" >> /home/cmccabe/Desktop/NGS/test/log 
echo "$filename"

Hi,
Could you give output of command find "$dir" -maxdepth 1 -mindepth 1 -printf '%T+\t%P\0' that we could see date format ?
Regards.

1 Like

find "$dir" -maxdepth 1 -mindepth 1 -printf '%T+\t%P\0'

2016-11-22+08:10:45.2369135580    32016-11-22+08:14:45.8369117830    12016-11-22+08:1

Thank you :).

FWIW - folder==directory

Directories are files of metadata - data about other files. So directories in many ways behave like regular files in terms of timestamps on the directory itself.

there is a filetime in epoch seconds for:

create  (not all UNIX filesystems track this, OSX may for example)
modify (inode)
access - latest read for example

    When the directory itself was first created (mkdir) -- set create (birth) date 
    When the directory was last opened and modified -- set modify date:
          an object in the directory was added
          an object in the directory was deleted
          note: opening an existing file and writing to it does not change the modify date 
            of the directory
change: set ownership, set access permissions (chmod, chown can do this)

So, the answer is: when you work with files in a directory some actions changethe modify date of that directory, some do not. You CANNOT prevent it.

You can use the touch command to "correct" a directory's modify time. If you are using a linux filesystem that supports create times use that. See your man page or --help for how to access the create (birth) times.

1 Like

Thank you both :).