Bash to select oldest folder in directory automatically and log process

The `bash` below uses the oldest folder in the specified directory and logs it. The goes though an analysis process and creates a log. My problem is that if there are 3 folders in the directory folder1,folder2,folder3 , the bash is using folder2 for the analysis eventhough folder1 is the oldest folder in the directory. Is the find command missing something? Also, is there a better way to log the folder used? That portion is in bold. Thank you :).

Bash

#!/bin/bash

dir=/home/cmccabe/Desktop/NGS/test
{
  read -r -d $'\t' time && read -r -d '' foldername
} < <(find "$dir" -maxdepth 1 -mindepth 1 -printf '%T+\t%P\0' | sort -z -r )
printf "The oldest folder is $foldername, created on $time" "and will be used for analysis on $(date "+%D %r")" >> /home/cmccabe/Desktop/NGS/test/log.txt

logfile=/home/cmccabe/Desktop/NGS/test/$foldername/process.log
for f in /home/cmccabe/Desktop/NGS/test/$foldername/bedtools/*.txt ; do
     echo "Start BedTools target base depth creation: $(date) - File: $f"
     bname=`basename $f`
     pref=${bname%%.txt}
     awk '{ sum += $7; n++ } END { if (n > 0) print sum / n; }' $f > /home/cmccabe/Desktop/NGS/test/$foldername/bedtools/${pref}_depth.bed
     echo "End BedTools target base depth creation: $(date) - File: $f"
done >> "$logfile"

edit: I must have had a typo as it seems fine now... thank you :).

1 Like