简体   繁体   中英

Tail command used in perl backticks

I'm trying to run a tail command from within a perl script using the usual backticks.

The section in my perl script is as follows:

$nexusTime += nexusUploadTime(`tail $log -n 5`);

So I'm trying to get the last 5 lines of this file but I'm getting the following error when the perl script finishes:

sh: line 1: -n: command not found

Even though when I run the command on the command line it is indeed successful and I can see the 5 lines from that particular.

Not sure what is going on here. Why it works from command line but through perl it won't recognize the -n option.

Anybody have any suggestions?

$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

ZZZ
zZt
Zz
ZZ
zyzzyvas

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.

这个问题的答案是在目标文件之前放置选项-n 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM