Tail command used in perl backticks Tail command used in perl backticks unix unix

Tail command used in perl backticks


$log has an extraneous trailing newline, so you are executing

tail file.log -n 5            # Tries to execute a program named "-n"

Fix:

chomp($log);

Note that you will run into problems if log $log contains shell meta characters (such as spaces). Fix:

use String::ShellQuote qw( shell_quote );my $tail_cmd = shell_quote('tail', '-n', '5', '--', $log);$nexusTime += nexusUploadTime(`$tail_cmd`);


ikegami pointed out your error, but I would recommend avoiding external commands whenever possible. They aren't portable and debugging them can be a pain, among other things. You can simulate tail with pure Perl code like this:

use strict;use warnings;use File::ReadBackwards;sub tail {    my ($file, $num_lines) = @_;    my $bw = File::ReadBackwards->new($file) or die "Can't read '$file': $!";    my ($lines, $count);    while (defined(my $line = $bw->readline) && $num_lines > $count++) {        $lines .= $line;    }    $bw->close;    return $lines;}print tail('/usr/share/dict/words', 5);

Output

ZZZzZtZzZZzyzzyvas

Note that if you pass a file name containing a newline, this will fail with

Can't read 'foo': No such file or directory at tail.pl line 10.

instead of the more cryptic

sh: line 1: -n: command not found

that you got from running the tail utility in backticks.


The answer to this question is to place the option -n 5 before the target file