通过shell_exec执行sed命令没有被执行

时间:2022-04-11 17:32:32

I want to execute a shell command after clicking on a button inside of a html code, so:

我想在单击html代码中的按钮后执行shell命令,所以:

In my html code:

在我的HTML代码中:

<form action=execute.php method="post">
    <input name="submit" type="submit" value="Reset">
</form>

execute.php:

execute.php:

<?php
    $output = shell_exec("sed -i '2,3d' filename.txt");
    //$output = shell_exec("cat filename.txt");
    echo "<pre>$output</pre>";

    $url = htmlspecialchars($_SERVER['HTTP_REFERER']);   
    echo "<a href='$url'>Back</a>"; 
?>

The purpose is to remove all lines of a text file but the very first one.

目的是删除文本文件的所有行,但第一个。

I think that the php code is being properly executed since if I modify the shell command by a simple cat, it works as expected, but I can't figure out why it does nothing when the command to execute is that sed expression.

我认为php代码正在被正确执行,因为如果我通过一个简单的cat修改shell命令,它按预期工作,但是当我执行的命令是sed表达式时,我无法弄清楚为什么它什么都不做。

I've verified that such sed command works when executed directly in CLI and I have also discarded any permissions issue since I chmoded "filename.txt" to 777. In fact if change the php code to append some text to the file it also works. For example:

我已经验证了这样的sed命令在CLI中直接执行时有效,我也放弃了任何权限问题,因为我将“filename.txt”编码为777.实际上如果更改php代码将一些文本附加到文件中它也可以工作。例如:

$output = shell_exec("echo hi >> filename.txt");

After looking for info I realized that what I want can be done directly with php with:

在寻找信息后,我意识到我想要的东西可以直接使用php完成:

file_put_contents("filename.txt", "");
file_put_contents("filename.txt", "First_line_content");

But now I'm just curious about why my sed command didn't work.

但现在我只是好奇为什么我的sed命令不起作用。

I'm running LAMP in an Ubuntu desktop with following sed version:

我正在使用以下sed版本在Ubuntu桌面上运行LAMP:

$ sed --version
sed (GNU sed) 4.2.2

1 个解决方案

#1


1  

As sed creates a temp file in the same directory as the file, the script must have write permissions to this directory.

当sed在与文件相同的目录中创建临时文件时,该脚本必须具有对此目录的写入权限。

#1


1  

As sed creates a temp file in the same directory as the file, the script must have write permissions to this directory.

当sed在与文件相同的目录中创建临时文件时,该脚本必须具有对此目录的写入权限。