Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script: Get name of last file in a folder by alphabetical order

Tags:

shell

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;
like image 456
yan Avatar asked Jul 02 '10 07:07

yan


1 Answers

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)
like image 63
Sjoerd Avatar answered Oct 21 '22 08:10

Sjoerd