如何检查命令的退出状态?
How can I check an exit status of a command?
我有一个代码片段:
my @array=("abc","def", "ghi");
print "I am testing exit code\n";
grep /lan/, @array;
if ($?) {
print "status is 0\n";
}
else {
print "Status is 1\n";
}
我在输出中得到“状态为 1”,但我想要“状态为 0”。根据我的理解,在@array
中,没有找到“lan”,因此退出状态必须是非零的,因此应该打印“status is 0”。
为什么 Perl 没有给出正确的退出代码?如果我上面的理解是错误的,请对退出代码理论给出正确的想法?
这是对 $? special variable. You would only check that variable when you execute an external command via system
, backticks, etc. Refer to Error variables 进一步详细信息的误用。
在您的代码中,grep is a Perl builtin function; it should not be confused with the grep
unix utility 同名。
您可以检查 return 状态,而不是尝试检查退出状态:
use warnings;
use strict;
my @array=("abc","def", "ghi");
print "I am testing array\n";
if (grep /lan/, @array) {
print "lan is in array\n";
}
else {
print "lan is not in array\n";
}
我有一个代码片段:
my @array=("abc","def", "ghi");
print "I am testing exit code\n";
grep /lan/, @array;
if ($?) {
print "status is 0\n";
}
else {
print "Status is 1\n";
}
我在输出中得到“状态为 1”,但我想要“状态为 0”。根据我的理解,在@array
中,没有找到“lan”,因此退出状态必须是非零的,因此应该打印“status is 0”。
为什么 Perl 没有给出正确的退出代码?如果我上面的理解是错误的,请对退出代码理论给出正确的想法?
这是对 $? special variable. You would only check that variable when you execute an external command via system
, backticks, etc. Refer to Error variables 进一步详细信息的误用。
在您的代码中,grep is a Perl builtin function; it should not be confused with the grep
unix utility 同名。
您可以检查 return 状态,而不是尝试检查退出状态:
use warnings;
use strict;
my @array=("abc","def", "ghi");
print "I am testing array\n";
if (grep /lan/, @array) {
print "lan is in array\n";
}
else {
print "lan is not in array\n";
}