Reputation: 3022
I have the below bash
that searches a specific directory and returns the earliest folder in that directory. The bash
works great if their are no subfolders within each folder. If there is those are returned instead of the main folder. I am not sure why this is happening or how to fix it. Thank you :).
For example,
/home/cmccabe/Desktop/NGS/test
is the directory searched and in it there are two folder, R_1 and R_2
output
The earliest folder is: R_1
However, if /home/cmccabe/Desktop/NGS/testhas
R_1 and within it testfolderand
R_2 and testfolder2 within it`
output
The earliest folder is: testfolder
Bash
cd /home/cmccabe/Desktop/NGS/test
folder=$(ls -u *"R_"* | head -n 1) # earliest folder
echo "The earliest folder is: $folder"
Upvotes: 0
Views: 28
Reputation: 295756
ls
is the wrong tool for this job: Its output is built for humans, not scripts, and is often surprising when nonprintable characters are present.
Assuming you have GNU find
and sort
, the following works with all possible filenames, including those with literal newlines:
dir=/home/cmccabe/Desktop/NGS/test # for my testing, it's "."
{
read -r -d $'\t' time && read -r -d '' filename
} < <(find "$dir" -maxdepth 1 -mindepth 1 -printf '%T+\t%P\0' | sort -z -r )
...thereafter:
echo "The oldest file is $filename, with an mtime of $time"
For a larger discussion of portably finding the newest or oldest file in a directory, including options that don't require GNU tools, see BashFAQ #99.
Upvotes: 1
Reputation: 138
You should read about ls, the -u option doesn't do what you think it does. The following are the relevant options:
So what you actually need is:
$ ls -trd
Or:
$ ls -utrd
Upvotes: 1