Last Updated: October 06, 2020
·
6.676K
· projectcleverweb

Super easy colors in ANY command line

I love having colors in my command line, they just make it so much easier to read and understand information. So I put together this script to make life easier. I don't have mac to test this on but it should work just the same as it does on linux.

Prerequisites

  • PHP installed and added to your $PATH
  • Download ANSICON, and install it (windows only)
     

  • Notice 1: Linux will automatically add php to your path if installed via apt-get or yum

  • Notice 2: Currently the ANSICON source on github is incomplete, and does not contain the x86 and x64 folders. The download link supplied is to one of my own repos that has the complete version of ANSICON in it. I do not own or contribute to ANSICON.

The Script

The script will soon become apart of a larger project of mine, but of course you can play with the current working version. Either copy & paste from below or get it from Github.

<?php 
/**
 * @copyright Nicholas Jordon
 */
class sh_color {
    private $txt_colors = array();
    private $txt_styles = array();
    private $bg_colors  = array();

    public function __construct(){
        // Set up colors
        $this->txt_colors = array(
            // regular
            'gray'         => '30',
            'red'          => '31',
            'green'        => '32',
            'yellow'       => '33',
            'blue'         => '34',
            'purple'       => '35',
            'cyan'         => '36',
            'white'        => '37',
            // light
            'light_gray'   => '90',
            'light_red'    => '91',
            'light_green'  => '92',
            'light_yellow' => '93',
            'light_blue'   => '94',
            'light_purple' => '95',
            'light_cyan'   => '96',
            'light_white'  => '97'
        );
        $this->txt_styles = array(
            'regular'      => '0',
            'bold'         => '1',
            'dark'         => '2', // this + gray = black
            'underline'    => '4',
            'invert'       => '7',
            'strike'       => '9'
        );
        $this->bg_colors = array(
            // regular
            'gray'         => '40',
            'red'          => '41',
            'green'        => '42',
            'yellow'       => '43',
            'blue'         => '44',
            'purple'       => '45',
            'cyan'         => '46',
            'white'        => '47',
            // light
            'light_gray'   => '100',
            'light_red'    => '101',
            'light_green'  => '102',
            'light_yellow' => '103',
            'light_blue'   => '104',
            'light_purple' => '105',
            'light_cyan'   => '106',
            'light_white'  => '107'
        );
    }

    // Returns colored string
    public function color_string($string, $txt_color=NULL, $bg_color=NULL, $txt_style=NULL){
        $return = "";
        $style = '0;';
        if(isset($this->txt_styles[strtolower((string) $txt_style)])){
            $style = $this->txt_styles[strtolower((string) $txt_style)];
        }
        if(isset($this->txt_colors[strtolower((string) $txt_color)])){
            $return .= "\033[".$style.';'.$this->txt_colors[strtolower((string) $txt_color)] . "m";
        }
        else{
            $return .= "\033[".$style.';97'. "m";
        }
        if(isset($this->bg_colors[strtolower((string) $bg_color)])){
            $return .= "\033[".$this->bg_colors[strtolower((string) $bg_color)] . "m";
        }
        $return .=  $string . "\033[0m";

        return $return;
    }

    public function get_txtstyles() {
        return array_keys($this->txt_styles);
    }

    public function get_txtcolors() {
        return array_keys($this->txt_colors);
    }

    public function get_bgcolors() {
        return array_keys($this->bg_colors);
    }
}

$color = new sh_color;

// get arguments
$longopts = array(
    'no-stdin',
    'print-all'
);
$args = getopt('s:S:c:C:',$longopts);

// stdin
$stdin = '';
if(!isset($args['no-stdin'])){
    if(!posix_isatty(STDIN)){$stdin = substr(file_get_contents('php://stdin'),0,-1);}
}

// test if arguments exist
if(empty($args['c'])){
    $args['c'] = NULL; // prevents error
}
if(empty($args['C'])){
    $args['C'] = NULL; // prevents error
}
if(empty($args['S'])){
    $args['S'] = NULL; // prevents error
}

if(empty($args['s'])){
    if(empty($stdin)){
        // error out if no string
        $args['s'] = 'ERROR: String is empty, please use STDIN or argument -s';
        $args['S'] = 'dark';
        $args['c'] = 'gray';
        $args['C'] = 'light_red';
    }
    else{
        $args['s'] = (string) $stdin;
        $str_switch = TRUE;
    }
}

if(isset($args['print-all'])){
    // print all the possiblities
    $output = '';
    foreach ($color->get_txtstyles() as $value) {
        $output .= $color->color_string('This is the txt style: '.$value, 'green', NULL, $value).PHP_EOL;
    }
    foreach ($color->get_txtcolors() as $value) {
        $output .= $color->color_string('This is the txt color: '.$value, $value).PHP_EOL;
    }
    foreach ($color->get_bgcolors() as $value) {
        $output .= $color->color_string('This is the bg color: '.$value, 'gray', $value, 'dark').PHP_EOL;
    }
}
else{
    // or print the inputs
    $output = $color->color_string($args['s'], $args['c'], $args['C'], $args['S']);
}

if(isset($str_switch) || isset($args['print-all'])){echo $output;}
else{echo $stdin.$output;}

Usage

NOTE: All examples assume the script is located in a file called color.php and it is located in the current directory.

The only required variable is a string supplied via either the -s argument or STDIN. This means both of the following will work without error:

php color.php -s "my name is frank"

echo my name is frank | php color.php

NOTE: Right now the default text color is white, and it is hard-coded in. A future build will likely allow this to be changed on-the-fly.

However, if both STDIN and -s are provided, STDIN will not be modified and it will be prepended to -s.

php color.php -s "hello, " -c yellow | php color.php -s Frank -c red

The above example would print "hello, Frank" where 'hello, ' is yellow, and 'Frank' is red.

Please note: Quotes are only required around a string if it has a space character in it.

Other Variables

Unlike the string variable, the remaining variables are not required, but each must use their respective argument.

The first optional argument is -c which colors the text of the string (see Ex 2). The next argument is -C which colors the background of the string (see Ex 3). And then there is the -S argument, which allows changing the style of the text (see Ex 4).

There is also the --no-stdin argument which will discard the STDIN string. This is more for future compatibly, which may allow STDIN to supply settings or other information.

Finally, You can easily view an example of all the colors and styles available by using the --print-all argument (see Ex 1). Please keep in mind this will discard all the other variables.

Examples

Ex 1:

This will print all the possible colors and styles, but will ignore all other supplied variables, including STDIN.

php color.php --print-all

Ex 2:

This will show the git diff short-stat where just the text is yellow.

git diff --shortstat | php color.php -c light_yellow

Ex 3:

(Linux) This will show the current directory with blue text on a white background.

pwd | php color.php -c blue -C white

Ex 4:

This will show the string "task complete: Make example #4" where "Make example #4" has a strike through it.

echo "task complete: " | php color.php -s "Make example #4" -S strike

Ex 5:

(Linux) Assuming you put the function git-unpushed into your ~/.bashrc file, the following would print "Not Pushed: 2" in a bold green text, given you have 2 commits ready to be pushed to Github in this directory.

function git-unpushed {
    brinfo=$(git branch -v)
    if [[ $brinfo =~ ("[ahead "([[:digit:]]*)]) ]]
    then
        echo "Not Pushed: ${BASH_REMATCH[2]}"
    fi
}

git-unpushed | php color.php -c green -S bold

 
 
 

Thanks for reading

If you enjoyed what I wrote, consider upvoting this protip or endorsing me.
If you want to see more of my stuff, you can see other protips I have written or visit my profile.

1 Response
Add your response

The download lnk for windows is not working correctly?

over 1 year ago ·