Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I'm googling for this, but the terms are so generic I'm getting way too many false positives, so what the hey, I'll ask here. I'm sure there's a simple answer but I don't generally script in *nix.

I'm trying to write a database refresh script to our test environment. The backups are mounted from an smbfs share, something like /data/backups/prod, but the subfolders get a little tricky. It looks like myproddbserver/yyyymmdd, with a bunch of files underneath.

I want to execute a command restore that will collect the files with known names from the most recent yyyymmdd directory. For example, if I had:


I would want to restore myproddbserver/20130731/foo.bak and myproddbserver/20130731/bar.bak.

How would I reliably get those paths?

share|improve this question

marked as duplicate by Gilles, slm, jasonwryan, Renan, Anthon Aug 14 '13 at 4:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 1 down vote accepted

Since you are using a yyyymmdd format, a numerical sort will work fine. The fastest way will be using the sort command:

newest_dir=$(printf '%s\n' myproddbserver/* | sort -rn | head -n1)

You can also do this in pure bash:

for d in myproddbserver/*; do
    (( d > newest )) && newest=$d

printf '%s\n' "${newest_files[@]}"

The bash version is likely slower, but will handle all possible filenames. The sort method will fail if any filenames contain a newline character.

share|improve this answer
Works like a champ; exactly what I needed. Thanks. –  Jeremy Holovacs Aug 13 '13 at 17:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.