Oihana PHP Commands

makeCommand.php

Table of Contents

Functions

makeCommand()  : string
Generates a complete shell command string, optionally including a pipeline.

Functions

makeCommand()

Generates a complete shell command string, optionally including a pipeline.

makeCommand(array<string|int, string>|string|null $command[, array<string|int, string>|string|null $args = null ][, CommandOptions|null $options = null ][, string|null $previous = null ][, string|null $post = null ]) : string

This function builds a shell command from a central main command, optional arguments/options, and optional commands to prepend ($previous) or append ($post) in a pipeline (|).

The main command can be provided as a string or an array (which will be joined by spaces). Arguments and options can also be strings or arrays of strings.

The $options parameter allows adding global prefixes such as sudo or running the command as another user.

If the main command is null, only the pipeline between $previous and $post is generated, and arguments or options are ignored.

Parameters
$command : array<string|int, string>|string|null

The main command to run, either as a string (e.g. 'ls') or an array of parts (e.g. ['wp', 'post', 'list']).

$args : array<string|int, string>|string|null = null

Arguments and options for the main command (e.g. '-la' or ['--format=ids']).

$options : CommandOptions|null = null

Global command options such as sudo or user context.

$previous : string|null = null

Command to prepend before the main command, for pipelines (e.g. 'cat file.txt').

$post : string|null = null

Command to append after the main command, for pipelines (e.g. 'grep "error"').

Tags
example
  1. Simple command with arguments
$cmd = $this->makeCommand( 'ls' , '-la' ) ;
// Outputs: "ls -la"
  1. Command as an array (safer against shell injection)
$cmd2 = $this->makeCommand(['wp', 'post', 'list'], '--format=ids');
// Outputs: "wp post list --format=ids"
``

3. Command with options (sudo/user)
```php
$options = new CommandOptions(['sudo' => true, 'user' => 'www-data']);
$cmd     = $this->makeCommand('wp cache flush', options: $options );
// Outputs: "sudo -u www-data wp cache flush"
  1. Full pipeline: read a file, filter it, then count lines
$cmd = $this->makeCommand( 'grep "error"', previous: 'cat /var/log/syslog', post: 'wc -l');
// Outputs: "cat /var/log/syslog | grep "error" | wc -l"
  1. Pipeline without a central command (use case for $command = null)
$cmd = $this->makeCommand( previous: 'ls -1 /var/www', post: 'wc -l');
// Outputs: "ls -1 /var/www | wc -l"
  1. Arguments and options are logically ignored if the command is null
$cmd = $this->makeCommand(null, '--force', previous: 'echo "start"');
// Outputs: "echo "start"" (options and arguments are not added)
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

The final full command string to execute, including any pipelines.


        
On this page

Search results