php - 使用多行 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
但是,当我运行它时,我没有得到任何输出。为什么是这样?
解决方案
您应该始终对要替换到命令行的变量进行转义,PHP 提供了一个函数escapeshellarg()
来执行此操作。
$output = shell_exec("/path/to/bash/script.sh " . escapeshellarg($filechosen));
或者
$escaped = escapeshellarg($filechosen);
$output = shell_exec("/path/to/bash/script.sh $escaped");
推荐阅读
- javascript - 使用 PHP 在 HTML 网页中执行外部 python 脚本
- javascript - this.props.Values 未定义
- exchange-server - Exchange Web 服务 - 发送电子邮件错误“项目已过期”
- javascript - 点击 NextJS 播放 MP3
- graphql - Docusaurus v2 和 GraphQL Playground 集成
- php - Illuminate\Database\QueryException SQLSTATE[42S01]:基表或视图已存在:1050 表“发票”已存在
- python-3.x - 将字符串拆分为名字和姓氏的最简单方法是什么?
- ubuntu - 尝试安装这样的包时出错“@u-wave/react-youtube”:“github:u-wave/react-youtube”
- angular - 错误类型错误:无法读取 null 的属性“附加”
- discord - 如何对所有成员隐藏特定频道(更新)?