【问题标题】:Error running Unix command from Perl从 Perl 运行 Unix 命令时出错
【发布时间】:2023-04-03 07:14:01
【问题描述】:

我正在尝试通过 Perl 脚本将输出和错误重定向到 Unix 中的文件。

该命令在 Unix 中运行良好,但在运行 Perl 脚本时抛出错误 sh: & is unexpected。我也尝试使用转义字符

命令:

`ls -lrt $myfile >>& $output`

也用过命令:

`ls -lrt $myfile >> $output 2>&1` - got ambiguous output redirect error

【问题讨论】:

  • 你想完成什么?无论如何,您尝试做的事情很有可能最好在 perl 中本地完成。
  • 我正在尝试将 unix 命令的输出和错误重定向到 perl 脚本内的文件中

标签: perl unix sh perl-module mod-perl


【解决方案1】:

反引号使用/bin/sh。您正在尝试重定向 STDOUT 和 STDERR?语法是:

>$output 2>&1

您还需要将文件名转换为 shell 文字。例如,它们可能包含空格,甚至更糟。

use String::ShellQuote qw( shell_quote );

my $cmd = shell_quote('ls', '-lrt', $myfile);
$cmd .= '>'.shell_quote($output).' 2>&1';
`$cmd`

【讨论】:

  • 这不起作用我试过了。它正在抛出“模棱两可的输出重定向”。
  • 何时使用反引号?
  • 不,/bin/sh 不是 /bin/csh。
  • 你为什么说bash和csh???问题是关于 Perl 中的反引号,它使用/bin/sh。我真的不在乎你在csh 或bash 中得到什么结果。当你还没有尝试过时,不要再说解决方案出错了。
  • 谢谢。那么有什么方法可以在 csh 或 tcsh 中运行相同的命令或强制它使用 sh/ksh shell 执行这些命令?
【解决方案2】:

试试这个并确保 myfile 和 output 有值

$myfile='src';
$output='myoutput';
`ls -lrt $myfile >> $output 2>&1`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 2014-05-25
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多