php cli shell script cheatsheet

Shebang

#!/usr/bin/php
<?php

Change working directory to script directory

$workDir = realpath(dirname(__FILE__));
chdir($workDir);

Arguments

$_SERVER['argv'][0] // = scriptname (myscript.php)

$_SERVER['argv'][1] // = first cmd argument "foo" (myscript.php foo)

Example argument handling:

$args = $_SERVER['argv'];
array_shift($args); // remove scriptname from args

$params['foo'] = false;

foreach ($args as $arg) {
  $arg = str_replace('--', '', $arg);
  $arg_parts = explode('=', $arg);
  $parameter_name = $arg_parts[0];
  $parameter_value = (isset($arg_parts[1])) ? $arg_parts[1] : null;
 
  if ($parameter_name == 'foo') {
    $params['foo'] = $parameter_value;
  } 
}

Get Environment Variable

$certbotDomain = getenv('CERTBOT_DOMAIN');

Write to stderr

fwrite(STDERR, “hello, world\n”);

Exit code

exit(1);

Execute a shell command and return the output

$output = shell_exec('uname -r');

Disable output buffering - direct streaming output

// Turn off output buffering
ini_set('output_buffering', 'off');
ob_implicit_flush(true);

system('ls -la');

Disable xdebug html output

ini_set('html_errors', false);

Color output

Colors: https://misc.flogisoft.com/bash/tip_colors_and_formatting

echo "\033[31mERROR: $message \033[33mLine $lineNumber \033[39m$line\n";

Background color:

echo "\033[31;43mRed on yellow background\n";

Reset colors to defaults:

echo "\033[0m";

printf

cutoff after 4 chars:

printf("%-4.4s", 'abcdefghi');  // abcd

color code counts as 5 chars (\033, [, 3, 5, m), so 5 needs to be added to the desired length (2 + 5 = 7):

printf("%-7.7s", "\033[35mNo"); // No

Direct inline execution

php -r '$parts = explode(".", phpversion()); echo $parts[0] . "." . $parts[1];'