The ls
command has a parameter -t
to sort by time. You can then grab the first (newest) with head -1
.
ls -t b2* | head -1
But beware: Why you shouldn’t parse the output of ls
My personal opinion: parsing ls
is dangerous when the filenames can contain funny characters like spaces or newlines.
If you can guarantee that the filenames will not contain funny characters (maybe because you are in control of how the files are generated) then parsing ls
is quite safe.
If you are developing a script which is meant to be run by many people on many systems in many different situations then do not parse ls
.
Here is how to do it safe: How can I find the latest (newest, earliest, oldest) file in a directory?
unset -v latest
for file in "$dir"/*; do
[[ $file -nt $latest ]] && latest=$file
done