justaguy
justaguy

Reputation: 3022

search returning subfolder not main folder in bash

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/testhasR_1 and within it testfolderandR_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

Answers (2)

Charles Duffy
Charles Duffy

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

Yuval
Yuval

Reputation: 138

You should read about ls, the -u option doesn't do what you think it does. The following are the relevant options:

  • -u - Tells ls to use last access time instead of last modification time when sorting by time. So by itself it does nothing, should be called with -t
  • -t - Sorts by time (of modification or access or something else), with newest first
  • -r - Reverses order of output
  • -d - Don't search directories recursively

So what you actually need is:

$ ls -trd  

Or:

$ ls -utrd

Upvotes: 1

Related Questions