Piping the result of ls to tail

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.


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

Tags:

Tail

Ls