将 PHP 变量发布到 bash 脚本中

将 PHP 变量发布到 bash 脚本中

我已使用 bash 脚本连接到 API,如下所示:

#!/bin/bash

curl "https://example.com/templates/search?field=template_id&    field=name" \
-H "Authorization: Bearer ----------------------------------------------------------------"

curl -X POST "https://example.com/audits" \
-d '{ "template_id": "template_28c5b7ec77f34ea7881b6a9ef9c01b91", "header_items": [ { "item_id": "f3245d40-ea77-11e1-aff1-0800200c9a66", "label": "Audit Title", "type": "textsingle", "responses": { "text": "${title}" } }, { "item_id": "f3245d43-ea77-11e1-aff1-0800200c9a66", "label": "Conducted By", "type": "textsingle", "responses": { "text": "John Citizen" } } ] }' \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ----------------------------------------------------------------"

这样就连接成功了。

然后我有一个 PHP 网页,其中包含一个表单,您可以在其中输入审核标题。当我在表单上按“保存”时,上面的脚本将运行并创建审核。但是,标题是 ${title} 而不是文本框的值。

是否有可能以这种方式将变量值发布到 bash 脚本?

答案1

更新时考虑了评论和聊天讨论。

PHP 代码将 shell 脚本作为 PHP 变量运行sh ./curl.sh $title$title理想情况下它应该正确引用$title数据以免混淆 shell)。因此,shell 脚本需要从其命令行参数 中选择标题,$*而不是从 shell 变量 中$title

发送的 JSON 文档是单引号的,这意味着$titleshell 不会看到变量扩展。

您需要暂时打破单引号字符串才能扩展变量:

-d '{ "template_id": "template...{ "text": "'"$*"'" }...

外面的双引号"'"$*"'"属于JSON文档,单引号内的内容属于shell。内部双引号引用该$*值(如果它包含空格和/或文件名通配模式)。

PHP 代码中还有一个额外的问题,这意味着 PHP$title变量从未正确设置。当这个问题解决后,它就按预期工作了。

相关内容