bashwildcard-expansion

bash script to find latest logfile


I want to find the latest logfile (.log extension) in a directory using a bash script.

At first my simple attempt worked ok

filename=`ls -t -c1 | head -1`

But when I admit that files other than logfiles could be found, this doesn't work because of wildcard expansion

filename=`ls -t -c1 *.log | head -1`

So I believe I have to read the ls command into an array or file, then process from there.


Solution

  • it seems to work fine ....

     Kaizen ~/so_test $ ls -lt -c1 z*
    -rw-r--r-- 1 Nitin None 318 Jun  5 21:59 ztestfile1
    -rwxrwxrwx 1 Nitin None 398 Jun  5 21:41 zawk1.sh
    

    alternatively you could try your hand with find ....

     Kaizen ~/so_test $ find . -mtime 0 -a -mtime -1 -iname "z*" | xargs ls -ltr | sort -k9 -r
     -rw-r--r-- 1 Nitin None 318 Jun  5 21:59 ./ztestfile1
     -rwxrwxrwx 1 Nitin None 398 Jun  5 21:41 ./zawk1.sh
    

    but this would need a bit of twik to suit your exact need.