I have a a shell script (myscript.sh
), which contains many bash commands. I want to run these command from a php file (index.php
).
I used exec
to execute the commands as following:
$contents = file_get_contents('../folder/myscript.sh');
$output = null;
$return_var = null;
exec($contents, $output, $return_var);
print_r($contents);
print_r($return_var);
print_r($output);
Here is the content of myscript.sh
VAR1=("somePath/allDirs")
ls
cd ..
ls
for DIR in "${VAR1[@]}"; do
echo "Name is $DIR"
done
pwd
....... other 5 lines of commands
All commands before the loop is working i.e: ls
and cd ..
and I got the output. However, the for loop is not working and it stop executing the rest of the commands after it.
My question is: how to execute this for loop that is inside shell script file from php file?
note: the for loop contains more command here I just put the echo to make the code easy to read and clear.
CodePudding user response:
Are you mutating the contents of the script at all? Why not just execute the script file rather than passing in the contents of the script? Regardless, if you must pass the contents directly to exec, pass it to bash -c
and escape the command contents:
$contents = file_get_contents('../folder/myscript.sh');
$output = null;
$return_var = null;
$contents = escapeshellarg($contents);
exec("bash -c $contents", $output, $return_var);