简体   繁体   English

从命令行在.php文件中运行shell命令

[英]Running shell commands in .php file from command-line

I have a series of shell commands I want to put in a program and execute the program from the command line. 我有一系列的shell命令,我想将它们放入程序中并从命令行执行该程序。 I decided to use PHP for this so currently I am trying to get the most basic shell commands to run. 我决定为此使用PHP,因此目前我正在尝试运行最基本的Shell命令。

Save as build.php 另存为build.php

<?php
shell_exec('cd ..');
echo "php executed\n";
?>

From the command-line 从命令行

php build.php

Output 产量

php executed

Php executes correctly but I'm still in the same directory. PHP可以正确执行,但是我仍然在同一目录中。 How do I get shell_exec( ... ) to successfully call a shell command? 如何获取shell_exec(...)以成功调用shell命令?

You need to change the cwd (current working directory) in PHP... any cd command you execute via exec() and its sister functions will affect ONLY the shell that the exec() call invokes, and anything you do in the shell. 您需要在PHP中更改cwd (当前工作目录)...通过exec()及其姐妹函数执行的任何cd命令将影响exec()调用调用的shell,以及您在shell中执行的任何操作。

<?php
    $olddir = getcwd();
    chdir('/path/to/new/dir');  //change to new dir
    exec('somecommand');

will execute somecommand in /path/to/new/dir . 将在/path/to/new/dir执行一些somecommand If you do 如果你这样做

<?php
    exec('cd /path/to/new/dir');
    exec('somecommand');

somecommand will be executed in whatever directory you started the PHP script from - the cd you exec'd just one line ago will have ceased to exist and is essentially a null operation. somecommand将在您从中启动PHP脚本的任何目录中执行-您仅somecommand执行的cd将不再存在,并且实质上是空操作。

Note that if you did something like: 请注意,如果您执行以下操作:

<?php
    exec('cd /path/to/new/dir ; somecommand');

then your command WOULD be executed in that directory... but again, once that shell exits, the directory change ceases to exist. 那么您的命令将在该目录中执行...但是同样,一旦该shell退出,该目录更改将不复存在。

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

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