gpt4 book ai didi

php - shell heredoc inside php heredoc

转载 作者:可可西里 更新时间:2023-10-31 23:28:42 26 4
gpt4 key购买 nike

我在 php 脚本中有类似的东西:

<?php
...
function log() {
// saving the log into a file.
exec(<<<BASH
cat >> $logFile <<EOF
$log
EOF
BASH
);
}
...

如您所见,两个 heredoc(BASH 是 php,EOF 是 shell)结束时人们认为是正确的,但是当我阅读创建的日志时,日志有这样的内容:

...
my logged string of an important event
EOF
my logged string of another important event
EOF
...

我检查了 apache 日志,它有以下条目:

sh: line 1: warning: here-document at line 0 delimited by end-of-file (wanted `EOF')

我做错了什么?

拜托,我知道还有许多其他实现,例如使用 php 函数或使用引号代替 heredocs。但我很好奇为什么在这种特殊情况下这不起作用。

编辑。我澄清了代码,因此更清楚我在谈论 php 运行 shell 命令。

最佳答案

PHP 案例的更新答案

假设我们有 test.php包含以下内容的文件:

<?php
function mylog() {
$logFile = 'test.log';
$log = 'test';

exec(<<<BASH
cat >> $logFile <<EOF
$log
EOF
BASH
);
}

mylog();

然后php test.php产生正确的东西(!):

rm -f test.log
php test.php
cat test.log

输出:

test

现在让我们缩进 Bash 部分:

<?php
function mylog() {
$logFile = 'test.log';
$log = 'test';

exec(<<<BASH
cat >> $logFile <<EOF
$log
EOF
BASH
);
}

mylog();

现在php test.php准确地产生你在你的问题:

rm -f test.log
php test.php
cat test.log

输出:

sh: line 2: warning: here-document at line 0 delimited by end-of-file (wanted `EOF')
test
EOF

显然,您的 Bash 部分缩进了,这是无效的 Bash 语法。所以你只需要删除 Bash 部分的缩进。至少,EOF不应缩进。

我认为 OP 意味着纯 Bash 的原始答案

exec执行命令,但您需要评估 bash 表达式。所以你需要 eval相反。

使用 eval 构建命令使用以下内容:

eval "$(
cat <<'EOF'

cat >> test.log <<EOF2
log contents
EOF2

EOF
)"

所以我们用"$(构造了一个Bash变量和 )" .在变量中,我们用 cat <<'EOF' 创建了一个 here-doc 字符串和 EOF ,其中单引号禁用参数替换,因此我们可以输入文字文本。(无评估)。然后我们写了log contents通过使用 <<EOF2 创建的另一个 here-doc 字符串和 EOF2 .

我们可能会保存 Bash 变量,然后根据需要多次使用它:

cmd="$(
cat <<'EOF'

cat >> test.log <<EOF2
log contents
EOF2

EOF
)"

rm test.log
eval "$cmd"; eval "$cmd"; eval "$cmd"
cat test.log

输出:

log contents
log contents
log contents

请参阅 here documents 的文档.

关于php - shell heredoc inside php heredoc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36943742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com