Running shell commands in .php file from command-line

后端 未结 1 1131
醉酒成梦
醉酒成梦 2021-01-28 18:25

I have a series of shell commands I want to put in a program and execute the program from the command line. I decided to use PHP for this so currently I am trying to get the mos

相关标签:
1条回答
  • 2021-01-28 18:52

    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
        $olddir = getcwd();
        chdir('/path/to/new/dir');  //change to new dir
        exec('somecommand');
    

    will execute somecommand in /path/to/new/dir. 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.

    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.

    0 讨论(0)
提交回复
热议问题