bash 执行带参数的sh脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19403384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:19:19  来源:igfitidea点击:

Execute sh script with parameters

phpbashshell

提问by indapublic

I have self-writed sh script, which contains contruction like "cd directory"

我有自己写的 sh 脚本,其中包含像“cd 目录”这样的结构

It is successfully running through terminal

它通过终端成功运行

. /path/to/script.sh param1 param2

I want to run this script through PHP

我想通过 PHP 运行这个脚本

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

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

not running correctly

运行不正常

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

running, but directory changing is not working

正在运行,但目录更改不起作用

Please, help. Thank you in advance

请帮忙。先感谢您

回答by Alma Do

You're starting your command with .- that will be interpreted as shell-source command, which is not what you want, obviously. Instead specify full path and do like:

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

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

-also, make sure your php user have permission to execute your sh-script and that PHP can use functions like exec()(they could be disabled by configuration)

-此外,请确保您的 php 用户有权执行您的 sh-script 并且 PHP 可以使用类似的功能exec()(它们可以通过配置禁用)

回答by Alexandre Nucera

You need to use quotes to send arguments, try this :

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

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

回答by geomagas

Aviod:

避免:

  1. Using the .notation, which would not work outside a bash shell. Use /bin/bash <yourscript>instead.

  2. Trying to cdto relative paths, as this confines the script's execution to be done from a specific location only

  3. Referencing (or implying) .bash_profileresources, as .bash_profileis executed only for login shells. If applicable, use .bashrcinstead.

  1. 使用.符号,这在 bash shell 之外不起作用。使用/bin/bash <yourscript>来代替。

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

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

回答by unni

Use

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

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

instead of

代替

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

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

...and make sure your shell script have executable permission for user who is running your script.

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

回答by slips

This function is disabled when PHP is running in safe mode. Check your php.ini file and make sure safe mode is turned off and it's not in 'disable_functions'.

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