简体   繁体   中英

tar extracting most recent file

Using bash, I have dir of /home/user/logs/

Aug 2 15:34 backup.20120802.tar.gz

Aug 3 00:26 backup.20120803.tar.gz

Aug 4 00:25 backup.20120804.tar.gz

Aug 15 06:39 backup.20120816.tar.gz

This gets updated every few days, but if something goes wrong I want it to automatically restore the most recent backup, how can I use bash only extract the most recent?

ls -t1 /home/user/logs/ | head -1

gives you the most recent modified file in /home/user/logs/. So you could do:

cd /dir/to/extract
tar -xzf "$(ls -t1 /home/user/logs/ | head -1)"

NOTE:
this assumes that /home/user/logs/ is flat and contains nothing but "*.tar.gz" files

If the time stamps may not always be reliable, try sorting by date.

ls -1 /home/user/logs/backup.*.tar.gz | sort -t . -k2rn | head -1

Ideally, you should not parse the output from ls , but if there are only regularly named files matching the wildcard, it may be the easiest solution; sort expects line-oriented input, anyway, so the task becomes more involved in the general case of completely arbitrary file names. (This may make no sense to you, but it would be perfectly okay as far as Unix is concerned to have a file named backup.20120816.tar.gz(newline)backup.20380401.tar.gz .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM