1

I have a .tar file that is transferred to our server every night by one of our client management systems. The file is a compressed .sql file which I need to uncompress and dump into our database.

The directory of the .tar file is /root/backups/premvet_sync/2012.07.17.10.09.19. As you can see the directory is a timestamp of when the file was uploaded to our server.

I am trying to create a cron job that CD's into the directory and then uncompresses it. The command I would usually use is something like this:

cd /root/backups/premvet_sync/2012.07.17.10.09.19 && tar -xvf backupfile.tar

Obviously that command would only run once (when the timestamp matches the cron job path). Is there anything I can do to CD into the newest directory?

The server is running Ubuntu 10.04 LTS if that makes any difference.

Update

For anyone who is interested, here is the final (working) bash script.

#!/bin/sh
# Untar backup database and dump into local mysql server.

echo "Finding latest backup directory"
dir=$(ls -td1 /root/backups/backup/* | head -1)

echo "Opening latest backup directory"
cd $dir

echo "Uncompress backup
tar -xvf backup.tar

echo "Dig down into correct directory"
cd $dir/backup/databases/MySQL

echo "mysqldump the compressed database file"
gunzip < backup.sql.gz | mysql -u USERNAME -pPASSWORD restore_db_name

echo "Done."
2
  • You could probably do with some sort of test to ensure that the sending side has done it's job before continuing. Perhaps check to see if the $dir/backup/databases/MySQL exists before running the tar command. If it does then the sending side didn't work ...
    – user9517
    Jul 17, 2012 at 9:51
  • Good idea, I presume I can just set it to halt if the directory doesn't exist.
    – dannymcc
    Jul 17, 2012 at 10:04

2 Answers 2

2

You can use ls -t to list the contents of /root/backups/premvet_sync/ in newest first order then pass that to head to get the first line

dir=$(ls -td1 /root/backups/premvet_sync/* | head -1)

will put /root/backups/premvet_sync/2012.07.17.10.09.19 in $dir so you can then

cd $dir
  • -t sort by modification time
  • -1 list one file per line
  • -d list directory entries instead of contents, ...
0
0
DATE=`date +%Y%m%d-%H%M%S`

mkdir -p /some/dir/$DATE

cd /some/dir/$DATE

etc

1
  • That doesn't produce a filename in the OPs stated format. As this is running after the file has been uploaded any portion of the date could be different from when it was created.
    – user9517
    Jul 17, 2012 at 9:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .