首页 > 解决方案 > 使用多行 PHP 变量作为执行 bash 脚本的参数

问题描述

在 PHP 中,我有一个返回多行文本的变量,类似于下面显示的内容。

*
*clefF4
*k[f#c#g#d#a#]
*d:
*M6/4

然后我想在 PHP 中使用这个变量作为执行 bash 脚本的参数。我的 PHP 代码如下($filechosen上面的文本字符串在哪里):

$output = shell_exec("/path/to/bash/script.sh $filechosen");
echo "<pre>$output</pre>";

下面是使用变量 ' $filechosen' 作为参数的极其简单的 bash 脚本:

#!/bin/bash

returnExpression=$(echo "$1" | grep 'k\[')
echo $returnExpression

但是,当我运行它时,我没有得到任何输出。为什么是这样?

标签: phpbash

解决方案


您应该始终对要替换到命令行的变量进行转义,PHP 提供了一个函数escapeshellarg()来执行此操作。

$output = shell_exec("/path/to/bash/script.sh " . escapeshellarg($filechosen));

或者

$escaped = escapeshellarg($filechosen);
$output = shell_exec("/path/to/bash/script.sh $escaped");

推荐阅读