Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run for loop that is inside shell script file from PHP file?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading