1

I want to parse a log file which is in /X on a Linux server. Below is the scenario :

  • Log files are pushed into /X at a regular interval of 5 minutes or when a log file size becomes 5MB
  • Now we are trying to make a parser which parses the latest created log file and gets the required information

How can I retrieve the file name of the most recent log file?

1
  • can you post a part of your log
    – aelor
    Commented Apr 28, 2014 at 6:03

3 Answers 3

1

Hi Abhinav if you only want to get file name you can use ls -Art | tail -n 1 command in your script.

0
1
#!/bin/bash

dir=/X
for file in "${dir}"/*; do
    [ -f "${file}" ] || continue
    [ "${file}" -nt "${newest}" ] && newest=${file}
done

echo "the most recentently modified file is '${newest}'"
0

ls -t will sort files by modification time (in your case it's the same as creation time, since the files are written once), and head -1 will give the first file, i.e. the most recent:

ls -t /X | head -1

A slight variation, which I think is more common, is listing in reverse (-r) and using tail:

ls -rt /X | tail -1
1
  • @AdrianFrühwirth good to know. However, I doubt any of the reasons listed are relevant for OP
    – shx2
    Commented Apr 28, 2014 at 6:07

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