0

I'm trying to do a bash one liner to get the latest logfile to cat and/or tail:

for i in /mnt/usbdrive/backup/filelog_*.log; do ls -t $i | head -n1 ; done

But get all of the matching files:

/mnt/usbdrive/backup/filelog_2020-06-03-09:00:01:345123169.log
/mnt/usbdrive/backup/filelog_2020-06-04-09:00:01:370667894.log
/mnt/usbdrive/backup/filelog_2020-06-04-19:15:27:274135912.log
/mnt/usbdrive/backup/filelog_2020-06-05-09:00:02:020131150.log
/mnt/usbdrive/backup/filelog_2020-06-06-09:00:02:238963148.log

Where am I going wrong?

Also, if I wanted to tail (or cat) that, would I have to declare another variable and tail -f that $variable ?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
J1raya
  • 320
  • 1
  • 6
  • 20
  • 3
    Please note: [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Cyrus Jun 06 '20 at 05:29

1 Answers1

1

I'm trying to do a bash one liner to get the latest logfile

You could use

latestfile=$(/bin/ls -t /mnt/usbdrive/backup/filelog_*.log | /bin/tail -1)

assuming you don't have spaces (or semicolons, etc...) in your file names

See ls(1), tail(1) and carefully read the documentation of GNU bash.

You'll better write your script in some other language (e.g. GNU guile, Python, Lua). See the shebang handling of execve(2).

You might also use stat(1) and/or gawk(1) and/or find(1). See glob(7) and path_resolution(7).

You could be interested by logrotate(8) and crontab(5) and inotify(7).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547