我正在通过perl脚本执行一些shell命令并捕获输出,如下所示,
$commandOutput = `cat /path/to/file | grep "some text"`;
Run Code Online (Sandbox Code Playgroud)
我还检查命令是否成功运行,如此
if(!$commandOutput)
{
# command not run!
}
else
{
# further processing
}
Run Code Online (Sandbox Code Playgroud)
这通常有效,我得到正确的输出.问题是,在某些情况下,命令本身不会产生任何输出.例如,有时我尝试的文本grep
将不会出现在目标文件中,因此不会提供任何输出.在这种情况下,我的脚本将其检测为"命令未运行",而不是真的.
在perl中区分这两种情况的正确方法是什么?
您可以使用它来了解命令是否失败或命令是否返回任何内容
$val = `cat text.txt | grep -o '[0-9]*'`;
print "command failed" if (!$?);
print "empty string" if(! length($val) );
print "val = $val";
Run Code Online (Sandbox Code Playgroud)
假设text.txt包含"123ab",您只想从中获取数字.