简体   繁体   English

如何从 php 运行 a.sh 文件?

[英]how to run a .sh file from php?

I am trying to run a shell script using php我正在尝试使用 php 运行 shell 脚本

shell script ( /home/scripts/fix-perm.sh ) is in the same server shell 脚本 ( /home/scripts/fix-perm.sh ) 在同一台服务器中

this is the code that i am trying这是我正在尝试的代码

<?php
echo shell_exec('/home/scripts/fix-perm.sh');
?>

the above code is not working上面的代码不起作用

am using linux server我正在使用 linux 服务器

can anybody please help me?有人可以帮我吗?

Shell exec takes a string which needs to be an actual command. Shell exec 需要一个字符串,它需要是一个实际的命令。 You are now passing it a filepath.您现在正在向它传递文件路径。 This is not interpreted as "execute the file at this path".这不会被解释为“在此路径上执行文件”。 You could do several things.你可以做几件事。

What you need to do is call the file with a program.您需要做的是使用程序调用该文件。 Call it with bash or sh as suggested in the comment:按照评论中的建议使用 bash 或 sh 调用它:

echo shell_exec('sh /home/scripts/fix-perm.sh');

Another option could be:另一种选择可能是:

$contents = file_get_contents('/home/scripts/fix-perm.sh');
echo shell_exec($contents);

I think the first option would be better however.不过,我认为第一种选择会更好。

It is important to note that all commands for executing external programs expect actual commands and not a filepath or something else.需要注意的是,所有用于执行外部程序的命令都需要实际命令,而不是文件路径或其他东西。 This goes for shell_exec , exec , passthru and others.这适用于shell_execexecpassthru等。

我不确定,但您可以先尝试在服务器上使用chmod +x /home/scripts/fix-perm.sh然后尝试...

first you need to make sure the file has the right permissions首先,您需要确保文件具有正确的权限

on your server chmod u+x /home/scripts/fix-perm.sh在您的服务器上chmod u+x /home/scripts/fix-perm.sh

then you run : echo shell_exec('sh /home/scripts/fix-perm.sh');然后你运行: echo shell_exec('sh /home/scripts/fix-perm.sh');

or if you want to output the results into a txt file:或者如果要将结果输出到 txt 文件中:

shell_exec('sh /home/scripts/fix-perm.sh > /home/scripts/log.txt &');

I got a similar problem evn i read all the posts.我在阅读所有帖子时遇到了类似的问题。 I want to execute a file.sh with a path to an another folder, and keep the result in my php page ( I don't want to close the.sh as it is looking foe css change).我想执行一个带有另一个文件夹路径的 file.sh,并将结果保存在我的 php 页面中(我不想关闭 .sh,因为它正在寻找 foe css 更改)。 Here what I try, but nothing append on php side:这是我尝试的,但 php 方面没有 append:

    <?php
    echo '<html><head>';
    echo'</head><body>';
        shell_exec('/bin/sh ../include/makeCss/makeWatch.sh'); 
    echo '</body></html>';
?>

and for the makeWatch.sh和 makeWatch.sh

 #!/bin/bash
sudo compass watch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM