Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore errors in shell_exec?

I get the output of a shell command in PHP as

$str = shell_exec("command");

and run the PHP script in terminal. When the shell command returns an error, it will be printed on the terminal. How can I tell shell_exec to return the command output only without any error output?

like image 776
Googlebot Avatar asked Oct 17 '22 11:10

Googlebot


1 Answers

You just have to discard error output by redirecting stderr to /dev/null

$str = shell_exec("command 2>/dev/null");

Non-error output - stdout - will be stored into $str as before.


Note that you don't need to suppress errors on shell_exec with the @ operator or wrap it into a try-catch block since shell_exec doesn't fail (you don't have a PHP runtime error).

It is the command it is asked to execute that may generate errors, the above approach will suppress those in the output.

Also some-command > /dev/null 2>&1 as other suggested is not what you want (if I understood correctly your question) since that would discard both error and non-error output.


A final note: you can decide to catch/discard stdout and/or stderr.

Of course you have to rely upon the fact that the command you're running send regular output to stdout and errors to stderr. If the command is not compliant to the standard (ex. sends everything to stdout) you're out of luck.

like image 89
Paolo Avatar answered Oct 29 '22 03:10

Paolo