Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run .sh file using exec Laravel PHP

I am trying to run a .sh file that will import a excel file to my database. Both files are in same directory inside the public folder. For some reason the exec command isn't being executed or neither any error occurs.

.sh file colde:

IFS=,
while read column1  
      do
        echo "SQL COMMAND GOES HERE"

done < file.csv | mysql --user='myusername' --password='mypassword' -D databasename;
echo "finish"

In my php file i have tried following:

$content = file_get_contents('folder_name/file_name.sh');
echo exec($content);

And:

shell_exec('sh /folder_name/file_name.sh');

Note: I can directly execute the sh file from gitbash however I want it to be done using function in Laravel controller. I'm using windows OS.

like image 655
Saurav Avatar asked Oct 29 '25 17:10

Saurav


2 Answers

you can use Process Component of Symfony that is already in Laravel http://symfony.com/doc/current/components/process.html

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('sh /folder_name/file_name.sh');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
like image 119
Alessandro Minoccheri Avatar answered Oct 31 '25 06:10

Alessandro Minoccheri


All of these answers are outdated now, instead use (Symfony 4.2 or higher):

$process = Process::fromShellCommandline('/deploy.sh');

Or

$process = new Process(['/deploy.sh']);

https://symfony.com/doc/current/components/process.html

like image 22
Alexander Kim Avatar answered Oct 31 '25 07:10

Alexander Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!