Create a gist now

Instantly share code, notes, and snippets.

@ormaaj /latest.bash
Last active Oct 12, 2015

What would you like to do?
Retrieve / assign latest mtime
# 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
if ! shopt -q nullglob; then
typeset -f +t "$FUNCNAME"
trap 'shopt -u nullglob; trap - RETURN' RETURN
shopt -s nullglob
IFS= typeset -a 'files=(${1:-*})'
typeset latest x
for x in "${files[@]}"; do
[[ -d $x || $x -ot $latest ]] || latest=$x
${2:+"$FUNCNAME"} "${2:-printf}" -- %s "$latest"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment