简体   繁体   中英

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

I have aa 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 ie: 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM