1

This question already has an answer here:

I have a directory with a bunch of log files. Something like this:

data170213.log
data170214.log
data170215.log
data170216.log

I'm interested in looking at the last entries of the most recent file and following it. If I know the most recent file is data170216.log, I can do that with

tail -f data170216.log

The problem is, I don't know what the name of the most recent file in the directory is. I can identify it though with

ls -1r *.log | head -1

What I can't work out is how to send the result of the command ls -1r *.log | head -1 to the command tail -f [FILE]

I tried the following, unsuccessfully

tail -f < ls -1r *.log | head -1

marked as duplicate by don_crissti, Stephen Kitt, Kusalananda, Jeff Schaller, Zachary Brady Feb 16 '17 at 17:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5

Use a command substitution:

tail -f "$(ls -1r *.log | head -n 1)"

This runs ls -1r *.log | head -n 1 in a subshell, takes its output, and builds a new command using that; so if the ls pipe outputs data170216.log, the command becomes

tail -f "data170216.log"

which is what you're after.

Note head -n 1 instead of head -1; the latter form is deprecated now.

1

You can use xargs in such cases. May be the simple and easy one is:

$ ls -1r *.log | sed -n 1p | xargs tail -f

Or:

$ ls -1r *.log | head -1 | xargs tail -f

Both work fine.

See man xargs

EXAMPLES:

Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces:

find /tmp -name core -type f -print | xargs /bin/rm -f

Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled:

find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f

Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled:

find /tmp -depth -name core -type f -delete

Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process)

Generates a compact listing of all the users on the system:

cut -d: -f1 < /etc/passwd | sort | xargs echo

Launches the minimum number of copies of Emacs needed, one after the other, to edit the files listed on xargs' standard input. This example achieves the same effect as BSD's -o option, but in a more flexible and portable way:

xargs sh -c 'emacs "$@" < /dev/tty' emacs

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