如何在 Perl 脚本中无限循环运行用户提供的命令,直到用户中止它?
我需要运行命令,直到我正在测试的系统失败,或者我中止脚本。我需要运行的命令可能会有所不同,因此我将其作为引号中的命令行参数。但我似乎无法使用系统命令运行命令行参数。这是我到目前为止所尝试的(使用@Cfreak提供的脚本编辑了我的尝试,即使我看到了同样的问题):
#!/usr/bin/perl
while(1)
{
print "Iteration #: $count\n";
$retval = system ($ARGV[1]);
if( $retval != 0 ) {
print "System call $ARGV[1] failed with code $retval\n";
}
$count++;
}
如果我这样做 ./run ls
我看到以下打印内容:
System call failed with code 65280
Iteration #: 1
System call failed with code 65280
Iteration #: 2
我在这里做错了什么?
I need to run a command till the system I'm testing fails, or I abort the script. The command I need to run may vary, so I'm taking it as a command-line argument in quotes. But I can't seem to be able to run a command-line argument using the system command. Here's what I tried so far (edited my attempt with the script that @Cfreak provided, even with which I see the same issue):
#!/usr/bin/perl
while(1)
{
print "Iteration #: $count\n";
$retval = system ($ARGV[1]);
if( $retval != 0 ) {
print "System call $ARGV[1] failed with code $retval\n";
}
$count++;
}
If I do
./run ls
I see the following prints:
System call failed with code 65280
Iteration #: 1
System call failed with code 65280
Iteration #: 2
What am i doing wrong here ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您想要 $ARGV[0] 而不是 $ARGV[1]。您可能还想检查以确保 $ARGV[0] 存在。
I believe that you want $ARGV[0] and not $ARGV[1]. You might also want to check to be sure that $ARGV[0] is present.
您对
system
的参数用单引号引起来。您根本不需要引号(尽管双引号也可以)实际上您还应该检查系统调用的返回值。如果调用成功,它应该返回 0:
如果你想在代码失败时停止脚本,那么只需使用
last
:You have single quotes around your argument to
system
. You don't need quotes at all (though double quotes would work)Really you should also check the return value of the system call. It should return 0 if the call succeeds:
If you want to stop the script when the code fails then just use
last
:65280 == 0xFF00,所以命令确实运行了(0xFF00 != -1),它没有因信号而死亡(0xFF00 & 0x7F == 0),并以退出代码 255 退出(0xFF00 >> 8 = = 0xFF == 255)。
所以我想你应该首先检查你运行的命令。嗯,根据你自己的输出,空字符串!也许您想要
$ARGV[0]
而不是$ARGV[1]
?使用
使用严格;使用警告;
!!!它本来可以避免这整个问题。65280 == 0xFF00, so the command did run (0xFF00 != -1), it did not die from a signal (0xFF00 & 0x7F == 0), and exited with exit code of 255 (0xFF00 >> 8 == 0xFF == 255).
So I guess you should start by checking what command you ran. Well, according to your own output, the empty string! Perhaps you want
$ARGV[0]
instead of$ARGV[1]
?Use
use strict; use warnings;
!!! It would have avoided this entire problem.