Differences between revisions 4 and 16 (spanning 12 versions)
Revision 4 as of 2009-09-15 18:08:36
Size: 1749
Editor: GreyCat
Comment: --
Revision 16 as of 2016-03-23 02:54:29
Size: 436
Editor: KerrySomme
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
<<Anchor(faq99)>>
== How can I get the newest (or oldest) file from a directory? ==
The intuitive answer of `ls -t | head -1` is wrong, because parsing the output of `ls` is [[ParsingLs|unsafe]]; instead, you should create a loop and compare the timestamps:

{{{
# Bash
files=(*) newest=${f[0]}
for f in "${files[@]}"; do
  if [[ $f -nt $newest ]]; then
    newest=$f
  fi
done
}}}

Then you'll have the newest file (according to modification time) in `$newest`. To get the oldest, simply change `-nt` to `-ot` (see `help test` for a list of operators), and of course change the names of the variables to avoid confusion.

Bash has no means of comparing file timestamps other than `mtime`, so if you wanted to get (for example) the most-recently-accessed file (newest by `atime`), you would have to get some help from the external command `stat(1)` (if you have it) or the [[BashLoadable|loadable builtin]] `finfo` (if you can load builtins).

Here's an example using `stat` from GNU coreutils 6.10 (sadly, even across Linux systems, the syntax of `stat` is not consistent) to get the most-recently-accessed file:

{{{
# Bash, GNU coreutils
newest= newest_t=0
for f in *; do
  t=$(stat --format=%X -- "$f") # atime
  if ((t > newest_t)); then
    newest_t=$t
    newest=$f
  fi
done
}}}

This also has the disadvantage of spawning an external command for every file in the directory, so it should be done this way only if necessary. To get the oldest file using this technique, you'd either have to initialize `oldest_t` with the largest possible timestamp (a tricky proposition, especially as we approach the year 2038), or with the timestamp of the first file in the directory, as we did in the first example.
Hello dear visitor. I'm Mittie Odaniel. One on the very best things inside the world for me personally is drawing but I have not made a dime with it's. Office supervising is just how I generate. His wife and him live in Arizona. My husband and I maintain an internet business. You might want to examine it here: http://Thatch22.Webs.com/<<BR>><<BR>>
<<BR>><<BR>>
My blog ... [[http://Thatch22.Webs.com/|how to be a mystery shopper]]

Hello dear visitor. I'm Mittie Odaniel. One on the very best things inside the world for me personally is drawing but I have not made a dime with it's. Office supervising is just how I generate. His wife and him live in Arizona. My husband and I maintain an internet business. You might want to examine it here: http://Thatch22.Webs.com/<<BR>><<BR>>

My blog ... how to be a mystery shopper

BashFAQ/099 (last edited 2016-03-23 09:25:56 by geirha)