bash - find the latest modified file and exec -


i want find out latest built rpm in directory , exec on it. similar below.

/bin/ls -1t srcdir/*.rpm | head -1  

but find command

find srcdir/*.rpm <get-only-the-most-recently-modified-file> -exec "<do-something>" 

two approaches -- 1 portable non-gnu platforms, other fast large directories (to extent allowed filesystem):


portable

what?

bashfaq #3: how can sort or compare files based on metadata attribute (newest / oldest modification time, size, etc)? relevant here. summarize:

latest= f in "$srcdir"/*.rpm;   [ "$f" -nt "$latest" ] && latest=$f done 

how?

[ "$a" -nt "$b" ] checks whether file named in variable a newer named in variable b in ksh-derived shells.


fast

...to clear, faster large directories, opposed faster in cases. said, it's adapted find (for instance) 5 or 10 newest files, or files except 5 or 10 newest, other approach not effectively.

what?

if have gnu tools (gnu find, gnu sort), consider following:

{ read -r -d ' ' mtime && ifs= read -r -d '' filename; } \   < <(find /directory -type f -iname "*.rpm" -printf '%t@ %p\0' | sort -z -r -n) 

this put latest file's time (in seconds-since-epoch) in shell variable mtime , name of file in filename. thus, can operate on file:

if [[ -e $filename ]];   # whatever arbitrary operations you're looking on resulting filename   cp -- "$filename" /path/to/where/to/copy fi 

how?

to explain how works:

find ... -printf '%t@ %p\0' 

...emits contents in format <epoch_mtime> <filename><nul>, epoch_mtime number of seconds since january 1st, 1970.

sort -z -r -n 

...then sorts output, expecting nul-delimited, on numbers @ beginning.

{ read -r -d ' ' mtime && ifs= read -r -d '' filename; } 

...reads content mtime variable first space in first line, , reads forward first nul filename variable.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -