Get the App
SLTechnology News&Howtos  ›  Development  › 

How to execute Shell commands in Laravel

Shulou Source: shulou.com Published: 2022-06-02 10:12:53 10月05日 Update

This article mainly describes how to execute Shell commands in Laravel, the article is very detailed, has a certain reference value, interested friends must read it!

Both shell_exec() and exec() can execute shell commands.

If your command doesn't know why it crashed, you won't know why--because shell_exec() and exec() don't throw exceptions, they just silently fail.

Here is my solution:

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; }}

It uses Symfony's Process component.

Using this method, I can throw a custom exception, log the command and output, or log it to the log to find the problem.

That's all for "How to execute Shell commands in Laravel." Thanks for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

Tags: Commands content reasons articles values interests just guys partners solutions methods logs more knowledge components industry solutions information channels this is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Redmi MariaDB Xiaomi MySQL