【问题标题】:Execute sh script with parameters执行带参数的sh脚本
【发布时间】:2013-10-24 13:34:26
【问题描述】:

我有自己编写的 sh 脚本,其中包含类似“cd 目录”的结构

终端运行成功

. /path/to/script.sh param1 param2

我想通过 PHP 运行这个脚本

shell_exec('. /path/to/script.sh param1 param2');

shell_exec('. /path/to/script.sh "param1" "param2"');

没有正确运行

shell_exec('/bin/bash /path/to/script.sh param1 param2');

正在运行,但无法更改目录

请帮忙。提前谢谢你

【问题讨论】:

  • 你最好使用完整路径而不是使用~,因为用户之间的HOME不同。
  • 您知道您正在运行的命令之间有不止一个区别,对吧?
  • @IgnacioVazquez-Abrams 偏离路线
  • cd directory中,directory是相对路径还是绝对路径?
  • @geomagas 我尝试了两种变体

标签: php bash shell


【解决方案1】:

您正在以. 开始您的命令 - 这将被解释为 shell-source 命令,这显然不是您想要的。而是指定完整路径并执行以下操作:

$result = shell_exec('/bin/bash /full/path/to/script.sh param1 param2');
//var_dump($result);

-另外,请确保您的 php 用户有权执行您的 sh 脚本,并且 PHP 可以使用像 exec() 这样的函数(它们可以通过配置禁用)

【讨论】:

  • 是的,脚本运行成功,但是像“cd my_directory”这样的结构不起作用
  • 你对cd有什么要求?您的脚本中发生了什么?为什么你不能在脚本中使用完整路径而不是 cd
  • cd_one (cd_one is function in my bash_profile) executing some routine operations cd_two (cd_two is function in my bash_profile) executing some routine operations
  • bash_profile 中的 cd_one 只是 cd first_directory 而 cd_two 是 cd second_directory
  • 替换您的别名以直接调用命令。还尝试使用完整路径(即完全摆脱 cd - 通常,最好避免使用它们,因为它们会导致代码可读性降低)
【解决方案2】:

当 PHP 在安全模式下运行时,该功能被禁用。检查您的 php.ini 文件并确保安全模式已关闭且不在“disable_functions”中。

【讨论】:

    【解决方案3】:

    您需要使用引号来发送参数,试试这个:

    $command_result = shell_exec('script.sh "'.$param1.'" "'.$param2."');
    

    【讨论】:

      【解决方案4】:

      避免:

      1. 使用 . 表示法,这在 bash shell 之外不起作用。请改用/bin/bash <yourscript>

      2. 尝试将cd 设置为相对路径,因为这将脚本的执行限制为只能从特定位置完成

      3. 引用(或暗示).bash_profile 资源,因为 .bash_profile 仅对登录 shell 执行。如果适用,请改用.bashrc

      【讨论】:

        【解决方案5】:

        使用

        shell_exec('./path/to/script.sh param1 param2');

        而不是

        shell_exec('. /path/to/script.sh param1 param2');

        ...并确保您的 shell 脚本对运行您的脚本的用户具有可执行权限。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-06-09
          • 2011-10-09
          • 1970-01-01
          • 2014-02-15
          • 2015-03-15
          • 2018-11-22
          • 1970-01-01
          相关资源
          最近更新 更多