Run Bash Command from PHP

r0skar picture r0skar · Jun 15, 2012 · Viewed 157.6k times · Source

I have a bash script, that I run like this via the command line:

./script.sh var1 var2

I am trying to execute the above command, after I call a certain php file.

What I have right now is:

$output = shell_exec("./script.sh var1 var2");
echo "<pre>$output</pre>";

But it doesn´t work. I tried it using exec and system too, but the script never got executed.

However when I try to run shell_exec("ls"); it does work and $output is a list of all files.

I am not sure whether this is because of a limitation of the VPS I am using or if the problem is somewhere else?

Answer

Robert K picture Robert K · Jun 15, 2012

You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.

$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);