パラメータを使用してPHPでbashスクリプトを実行する - 角括弧で問題が発生する

パラメータを使用してPHPでbashスクリプトを実行する - 角括弧で問題が発生する

私はこのPHPを持っています:

exec("/csvexport.sh $table");

次のbashスクリプトを実行します(テーブルをCSVにエクスポートします)。

#!/bin/bash
table=$1

mysql --database=db --user=user --password=pass -B -e "SELECT field1, field2, IF(field3 = '0000-00-00','0001-01-01',field3) AS field3 FROM mytable;" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > /home/backups/$table.csv

これは素晴らしい作品です。しかし、私はクエリが次のように動的であることを望みます。

$query = "SELECT field1, field2, IF(field3 = '0000-00-00','0001-01-01',field3) AS field3 FROM mytable;";
exec("/csvexport.sh $query $table");

bashを次のように変更した場合:

#!/bin/bash
query=$1
table=$2

mysql --database=db --user=user --password=pass -B -e "$query" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > /home/backups/$table.csv

すべてが「同じ」であっても、次のエラーが発生します。

sh: -c: line 0: syntax error near unexpected token `('

もしそうなら、PHPで渡されたクエリに角かっこが含まれている方法が気に入らないようです。

ベストアンサー1

PHPからシェルスクリプトにパラメータを渡します。

これは、「文字列」と拡張のために「二重引用符」をいつ使用するかについてです。

<?php

/* exec("/csvexport.sh $table"); */

/* double quote here because you want PHP to expand $table */
/* Escape double quotes so they are passed to the shell because you do not wnat the shell to choke on spaces */
$command_with_parameters = "/path/csvexport.sh \"${table}\"";
$output_from_command = "";
$command_success = "";

/* double quote here because you want PHP to expand $command_with_parameters, a string */
exec("${command_with_parameters}", $output_from_command, $command_success);

/* or to keep it simple */
exec("/path/csvexport.sh \"${table}\"");


/* show me what you got */
echo"${command_success}\n${output_from_command}\n";

?>

注:私はこの作品をテストしていません。

おすすめ記事