Last active
October 12, 2015 12:48
-
-
Save ormaaj/4029356 to your computer and use it in GitHub Desktop.
Retrieve / assign latest mtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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