public
Last active

Retrieve / assign latest mtime

  • Download Gist
latest.bash
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# Find the last modified file selected from a glob.
# Usage: latest <glob> <varname>
# Takes an optional glob and optional varname.
# glob defaults to '*'. If varname is set, assign to varname,
# else output to stdout.
function latest {
if [[ $FUNCNAME == "${FUNCNAME[1]}" ]]; then
unset -v x latest files
printf -v "$@"
elif (($# > 2)); then
printf '%s\n' "Usage: $FUNCNAME <glob> <varname>" 'Error: Takes at most 2 arguments. Glob defaults to *'
return 1
else
if ! shopt -q nullglob; then
typeset -f +t "$FUNCNAME"
trap 'shopt -u nullglob; trap - RETURN' RETURN
shopt -s nullglob
fi
 
IFS= typeset -a 'files=(${1:-*})'
typeset latest x
 
for x in "${files[@]}"; do
[[ -d $x || $x -ot $latest ]] || latest=$x
done
 
${2:+"$FUNCNAME"} "${2:-printf}" -- %s "$latest"
fi
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.