簡體   English   中英

如何從 PHP 文件運行 shell 腳本文件中的循環?

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

我有一個 shell 腳本 ( myscript.sh ),其中包含許多 bash 命令。 我想從 php 文件( index.php )運行這些命令。

我使用exec執行以下命令:

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

這是myscript.sh的內容

VAR1=("somePath/allDirs")
ls
cd ..
ls
for DIR in "${VAR1[@]}"; do
  echo "Name is $DIR"
done
pwd
....... other 5 lines of commands

循環之前的所有命令都在工作,即: lscd ..我得到了輸出。 但是,for 循環不起作用,它會停止執行其后的其余命令。

我的問題是:如何從 php 文件執行 shell 腳本文件中的這個 for 循環?

注意:這里的 for 循環包含更多命令,我只是放了 echo 以使代碼易於閱讀和清晰。

您是否完全改變了腳本的內容? 為什么不直接執行腳本文件而不是傳入腳本的內容呢? 無論如何,如果您必須將內容直接傳遞給 exec,請將其傳遞給bash -c並轉義命令內容:

$contents = file_get_contents('../folder/myscript.sh');
$output = null;
$return_var = null;
$contents = escapeshellarg($contents);
exec("bash -c $contents", $output, $return_var);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM