如何将PHP数组传递给BASH脚本?

coo*_*490 11 php linux arrays bash shell

我有一个PHP脚本和一个bash脚本.他们在同一个目录中.我正在从命令行运行php脚本,它将数组传递给bash脚本.我正在尝试执行以下操作:

  1. 将PHP数组传递给BASH脚本
  2. 从STDIN获取用户输入
  3. 将用户输入传递回PHP脚本以进行进一步处理

这是我的PHP脚本:

<?php
$a=array("red","green","blue","yellow");

$string = '(' . implode(' ', $a) . ')';  // (red green blue yellow)

$user_response = shell_exec('./response.sh $string');

// do something with $user_response

?>
Run Code Online (Sandbox Code Playgroud)

BASH脚本应该从STDIN读取数组并提示用户选择一个选项:

#!/bin/bash
options=$($1);   # (red green blue yellow) but this isn't working
i=0;
echo "select an option";
for each in "${options[@]}"
do
echo "[$i] $each"
i=$((i+1))
done

echo;

read input;
echo "You picked option ${options[$input]}";
# here's where I want to pass or export the input back to the 
# php script for further processing
Run Code Online (Sandbox Code Playgroud)

当我运行php脚本时,它不显示数组选项.

anu*_*ava 2

你的 shell 脚本可以这样写:

#!/bin/bash
options=("$@")

i=0
echo "select an option"
for str in "${options[@]}"; do
   echo "[$i] $str"
   ((i++))
done    
echo    
read -p 'Enter an option: ' input
echo "You picked option ${options[$input]}"
Run Code Online (Sandbox Code Playgroud)

然后你的 PHP 代码如下:

<?php
$a=array("red","green","blue","yellow");    
$string = implode(' ', $a);    
$user_response = shell_exec("./response.sh $string");

echo "$user_response\n";
?>
Run Code Online (Sandbox Code Playgroud)

但请记住,从 PHP 运行时输出将如下所示:

php -f test.php
Enter an option: 2
select an option
[0] red
[1] green
[2] blue
[3] yellow

You picked option blue
Run Code Online (Sandbox Code Playgroud)

即用户输入将在脚本输出显示之前出现。