views:

38

answers:

2

I have a folder with backups from a MySQL database that are created automatically. Their name consists of the date the backup was made, like so:

2010-06-12_19-45-05.mysql.gz  
2010-06-14_19-45-05.mysql.gz  
2010-06-18_19-45-05.mysql.gz  
2010-07-01_19-45-05.mysql.gz

What is a way to get the filename of the last file in the list, i.e. of the one which in alphabetical order comes last?

In a shell script, I would like to do something like

LAST_BACKUP_FILE= ???
gunzip $LAST_BACKUP_FILE;
+3  A: 
ls -1 | tail -n 1

If you want to assign this to a variable, use $(...) or backticks.

FILE=`ls -1 | tail -n 1`
FILE=$(ls -1 | tail -n 1)
Sjoerd
Wow, that was fast! And it works like a charm. Thanks!
How would I limit the ls to .gz files only in a fixed path? (Like: The last file with the extension .gz in the folder /home/xy/abc)
Just like you use `ls` normally, something like `ls -1 /home/xy/abc/*.gz`.
Sjoerd
+1  A: 

@Sjoerd's answer is correct, I'll just pick a few nits from it:

  1. you don't need the -1 option to enforce one path per line if you pipe the output somewhere:

    ls | tail -n 1
    
  2. you can use -r to get the listing in reverse order, and take the first one:

    ls -r | head -n 1
    
  3. gunzip some.log.gz will write uncompressed data into some.log and remove some.log.gz, which may or may not be what you want (probably isn't). if you want to keep the compressed source, pipe it into gunzip:

    gunzip < some.file.gz
    
  4. you might want to protect the script against situation when the dir contains no files, since

    gunzip $empty_variable
    

expands to just

    gunzip

and such invocation will wait indefinitely for data on standard input:

    latest="$(ls -r /some/where/*.gz | head -1)"
    if test -z "$latest"; then
      # there's no logs yet, bail out
      exit
    fi
    gunzip < $latest
just somebody
(1) Yup; (2) Yup; (3) or '`gzip -cd some.file.gz >some.file`' leaves the original compressed file around; (4) Yup - check results before using them.
Jonathan Leffler