Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Last active October 12, 2015 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ormaaj/4029356 to your computer and use it in GitHub Desktop.
Save ormaaj/4029356 to your computer and use it in GitHub Desktop.
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
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment