Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if shell command didn't run or produced no output

Tags:

shell

unix

perl

I am executing some shell commands via a perl script and capturing output, like this,

$commandOutput = `cat /path/to/file | grep "some text"`;

I also check if the command ran successfully or not like this,

if(!$commandOutput)
{
    # command not run!
}
else
{
    # further processing
}

This usually works and I get the output correctly. The problem is, in some cases, the command itself does not produce any output. For instance, sometimes the text I am trying to grep will not be present in the target file, so no output will be provided as a result. In this case, my script detects this as "command not run", while its not true.

What is the correct way to differentiate between these 2 cases in perl?

like image 308
Jenson Jose Avatar asked Feb 16 '23 13:02

Jenson Jose


1 Answers

you can use this to know whether the command failed or the command return nothing

$val = `cat text.txt | grep -o '[0-9]*'`;    
print "command failed" if (!$?);    
print "empty string" if(! length($val) );    
print "val = $val";

assume that text.txt contain "123ab" from which you want to get number only.

like image 185
pkm Avatar answered Feb 18 '23 02:02

pkm