Shell命令语法错误

时间:2013-06-07 05:02:43

标签: perl email pipe

有问题的2个例子:以下语句语法有什么问题(perl newbie):

$mailCmd = sprintf("echo $message | /usr/ucb/mail -s 'X Detected an Invalid Thing' %s", $people_list);

当我执行system($mailCmd)`$mailCmd`时,会产生:

sh: syntax error at line 2: `|' unexpected

另一个:

$message = "Invalid STUFF setup for ID $r.  Please correct this ASAP.\n" .
            "Number of thingies  = $uno \n"   .
            "Another thingy      = $id  \n" ;

这会产生:

sh: Number: not found
sh: Another: not found

提前致谢

1 个答案:

答案 0 :(得分:3)

第一个问题的直接原因是您正在执行以下命令,因为$message的内容以换行符结尾。

echo ...
| /usr/usb/mail ...

这两个问题都是shell命令构造不当造成的。修正:

use String::ShellQuote qw( shell_quote );
my $echo_cmd = shell_quote('echo', $message);
my $mail_cmd = shell_quote('/usr/ucb/mail',
   '-s' => 'X Detected an Invalid Thing',
   $people_list,
);
system("$echo_cmd | $mail_cmd");

完全避免使用echo和shell:

use IPC::Run3 qw( run3 );
my @cmd = ('/usr/ucb/mail',
   '-s' => 'X Detected an Invalid Thing',
   $people_list,
);
run3 \@cmd, \$message;