DEV Community

Cover image for Executing Shell Commands In Laravel
Bertug Korucu for Kodeas

Posted on

20 2

Executing Shell Commands In Laravel

Both shell_exec() and exec() do the job - until they don't.

If your command crash for some reason, you won't know - shell_exec() and exec() don't throw Exceptions. They just fail silently. 😱

So, here is my solution to encounter this problem:

use Symfony\Component\Process\Process;

class ShellCommand
{
    public static function execute($cmd): string
    {
        $process = Process::fromShellCommandline($cmd);

        $processOutput = '';

        $captureOutput = function ($type, $line) use (&$processOutput) {
            $processOutput .= $line;
        };

        $process->setTimeout(null)
            ->run($captureOutput);

        if ($process->getExitCode()) {
            $exception = new ShellCommandFailedException($cmd . " - " . $processOutput);
            report($exception);

            throw $exception;
        }

        return $processOutput;
    }
}
Enter fullscreen mode Exit fullscreen mode

It utilises Symfony's Process (which comes out of the box to Laravel).

With this way, I can throw a custom exception, log the command and the output to investigate, report it to my logs to investigate, etc.

No more failing silently 😇

Hope you like this little piece! If you do, please give it a ❤️

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (5)

Collapse
 
phpdevvn profile image
https://yhub.io Download video

Thank you so much!

Collapse
 
muetze profile image
Norman Huth

Simple use Laravel Processes:
laravel.com/docs/10.x/processes

Collapse
 
awaiscb profile image
Awais

Thanks Where to keep this file in project?

Collapse
 
bertugkorucu profile image
Bertug Korucu

In a smaller project, I'd create a "app/Helpers" directory

Collapse
 
reynoldgan profile image
reynold

Thanks!

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay