[英]How to pass a PHP array to a BASH script?
我有一個PHP腳本和一個bash腳本。 他們在同一個目錄中。 我正在從命令行運行php腳本,它將數組傳遞給bash腳本。 我正在嘗試執行以下操作:
這是我的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
?>
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
當我運行php腳本時,它不顯示數組選項。
我說最簡單的不是嘗試模擬內部bash數組,而是使用'normal'邏輯/后處理。 例如; 如果你只是將implode(' ', $a)
傳遞給bash腳本(你也應該通過escapeshellarg()
傳遞它escapeshellarg()
$a=array("red","green","blue","yellow");
$args = implode(' ', array_map('escapeshellarg', $a));
$user_response = shell_exec('./response.sh '. $args);
然后你可以使用bash遍歷參數
for each in $*; do
echo $each
done
您的解決方案的問題是Shell腳本的輸出實際上是PHP $response
變量:
SHELL腳本:
#!/bin/bash
echo "Before prompt"
read -p 'Enter a value: ' input
echo "You entered $input"
PHP腳本:
<?php
$shell = shell_exec("./t.sh");
echo "SHELL RESPONSE\n$shell\n";
php t.php
結果:
$ php t.php
Enter a value: foo
SHELL RESPONSE
Before prompt
You entered foo
您捕獲了Shell腳本的整個STDOUT
。
如果您希望簡單地將值傳遞給shell腳本,則選項$option_string = implode(' ', $array_of_values);
將為腳本單獨設置選項。 如果你想要一些更先進的東西(設置標志,分配東西等)試試這個( https://ideone.com/oetqaY ):
function build_shell_args(Array $options = array(), $equals="=") {
static $ok_chars = '/^[-0-9a-z_:\/\.]+$/i';
$args = array();
foreach ($options as $key => $val) if (!is_null($val) && $val !== FALSE) {
$arg = '';
$key_len = 0;
if(is_string($key) && ($key_len = strlen($key)) > 0) {
if(!preg_match($ok_chars, $key))
$key = escapeshellarg($key);
$arg .= '-'.(($key_len > 1) ? '-' : '').$key;
}
if($val !== TRUE) {
if((string) $val !== (string) (int) $val) {
$val = print_r($val, TRUE);
if(!preg_match($ok_chars, $val))
$val = escapeshellarg($val);
}
if($key_len != 0)
$arg .= $equals;
$arg .= $val;
}
if(!empty($arg))
$args[] = $arg;
}
return implode(' ', $args);
}
這將是您傳遞給命令行的最全面的解決方案。
如果您正在尋找一種方法來提示用戶(一般情況下),我會考慮留在PHP中。 最基本的方法是:
print_r("$question : ");
$fp = fopen('php://stdin', 'r');
$response = fgets($fp, 1024);
或者,為了支持驗證問題,多行,並且僅在CLI上調用:
function prompt($message = NULL, $validator = NULL, $terminator = NULL, $include_terminating_line = FALSE) {
if(PHP_SAPI != 'cli') {
throw new \Exception('Can not Prompt. Not Interactive.');
}
$return = '';
// Defaults to 0 or more of any character.
$validator = !is_null($validator) ? $validator : '/^.*$/';
// Defaults to a lonely new-line character.
$terminator = !is_null($terminator) ? $terminator : "/^\\n$/";
if(@preg_match($validator, NULL) === FALSE) {
throw new Exception("Prompt Validator Regex INVALID. - '$validator'");
}
if(@preg_match($terminator, NULL) === FALSE) {
throw new Exception("Prompt Terminator Regex INVALID. - '$terminator'");
}
$fp = fopen('php://stdin', 'r');
$message = print_r($message,true);
while (TRUE) {
print_r("$message : ");
while (TRUE) {
$line = fgets($fp, 1024); // read the special file to get the user input from keyboard
$terminate = preg_match($terminator, $line);
$valid = preg_match($validator, $line);
if (!empty($valid) && (empty($terminate) || $include_terminating_line)) {
$return .= $line;
}
if (!empty($terminate)) {
break 2;
}
if(empty($valid)) {
print_r("\nInput Invalid!\n");
break;
}
}
}
return $return;
}
因為括號在子shell中運行它們中的內容,這不是我想要的......
我會改變這個......
$string = '(' . implode(' ', $a) . ')';
對此......
$string = '"' . implode (' ', $a) . '"';
另外,在這里使用雙引號......
$user_response = shell_exec ("./response.sh $string");
或者爆發......
$user_response = shell_exec ('./response.sh ' . $string);
因此,我也會將BASH更改為簡單地接受單個參數,字符串,並將該參數拆分為數組以獲取我們的選項。
像這樣......
#!/bin/bash
IFS=' ';
read -ra options <<< "$1";
i=0;
echo "select an option";
for each in "${options[@]}"; do
echo "[$i] $each";
i=$((i+1));
done;
unset i;
echo;
read input;
echo "You picked option " ${options[$input]};
您可以將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]}"
然后讓你的PHP代碼如下:
<?php
$a=array("red","green","blue","yellow");
$string = implode(' ', $a);
$user_response = shell_exec("./response.sh $string");
echo "$user_response\n";
?>
但是請記住,從PHP運行時輸出將是這樣的:
php -f test.php
Enter an option: 2
select an option
[0] red
[1] green
[2] blue
[3] yellow
You picked option blue
即用戶輸入將在腳本輸出顯示之前到來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.