我正在尝试使用常用的反引号从 perl 脚本中运行 tail 命令。
我的 perl 脚本中的部分如下:
$nexusTime += nexusUploadTime(`tail $log -n 5`);
所以我试图获取此文件的最后 5 行,但在 perl 脚本完成时出现以下错误:
sh: line 1: -n: command not found
即使当我在命令行上运行命令时它确实成功并且我可以看到该特定的 5 行。
不知道这里发生了什么。为什么它在命令行下工作,但通过 perl 它无法识别 -n 选项。
有人有什么建议吗?
最佳答案
$log
有一个无关的尾随换行符,所以你正在执行
tail file.log
-n 5 # Tries to execute a program named "-n"
修复:
chomp($log);
请注意,如果日志 $log
包含 shell 元字符(例如空格),您将遇到问题。修复:
use String::ShellQuote qw( shell_quote );
my $tail_cmd = shell_quote('tail', '-n', '5', '--', $log);
$nexusTime += nexusUploadTime(`$tail_cmd`);
关于perl - perl 反引号中使用的 tail 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267050/