Use cmd commands in shell scripts - cakephp 3.0

Asked

Viewed 354 times

0

I was wondering if you can use native windows CMD commands from scripts made to run in the cakephp shell.

I already run tasks that run in cmd, but with the commands of the framework itself but would like to use other commands.

1 answer

2


I don’t quite understand the doubt, I suppose you want to create a shell in cakephp, such as:

namespace App\Shell;

use Cake\Console\Shell;

class HelloShell extends Shell
{
    public function main()
    {
        $this->out('Hello world.');
    }
}

But let it execute commands that exist on the machine.

Understand that commands running on CMD are mostly global executables.

To run Windows command you will obviously need to be on a Windows server and you will not necessarily need cakephp, but only php, in which case we have 3 functions:

  • exec - returns the program’s response in an array type reference (second parameter)

  • system - returns the response directly in the output, or if HTTP already prints as if the echo, it is also possible to take the last line of the output and the return response of the application (usually is a number)

  • shell_exec - Executes a command via "shell" and returns the result a string

It is important to note that if using arguments in commands it is necessary to use the escapeshellarg or escapeshellcmd

namespace App\Shell;

use Cake\Console\Shell;

class HelloShell extends Shell
{
    public function main()
    {
        $resposta = shell_exec('dir');

        $this->out($resposta);
    }

    public function raiz()
    {
        $resposta = shell_exec('dir \\');

        $this->out($resposta);
    }

    public function foo($pasta)
    {
        $resposta = shell_exec('dir ' . $pasta);

        $this->out($resposta);
    }
}

After saving the file, you should be able to execute the following commands:

  • Displays the contents of the current folder, usually the one that called the main script or varying from the larger application’s pointing (for example apache):

    bin/cake hello
    
  • Displays the contents of the root folder:

    bin/cake hello raiz
    
  • Displays the contents of a folder you determine:

    bin/cake hello foo /a/b/c
    

They will show something like:

O volume na unidade C não tem nome.
O Número de Série do Volume é AEE4-3225

Pasta de C:\Users\Guilherme\Exemplo

18/08/2016  23:06    <DIR>          .
18/08/2016  23:06    <DIR>          ..
14/07/2016  23:14    <DIR>          pasta
28/04/2016  21:03                21 .bash_history
               1 arquivo(s)          21 bytes
              3 pasta(s)   267.064.922.112 bytes disponíveis

Browser other questions tagged

You are not signed in. Login or sign up in order to post.