logoalt Hacker News

jphyesterday at 5:36 PM4 repliesview on HN

If you want a quick easy way to add some colors to your own shell scripts:

    export STDOUT_COLOR_START=''
    export STDOUT_COLOR_STOP=''
    export STDERR_COLOR_START=''
    export STDERR_COLOR_STOP=''
In your shell script:

    print_stdout() {
        printf %s%s%s\\n "${STDOUT_COLOR_START:-}" "$*" "${STDOUT_COLOR_STOP:-}"
    }

    print_stderr() {
        >&2 printf %s%s%s\\n "${STDERR_COLOR_START:-}" "$*" "${STDERR_COLOR_STOP:-}"
    }
Source: https://github.com/sixarm/unix-shell-script-kit

The source also has functions for nocolor, and detecting a dumb terminal setup that doesn't use colors, etc.


Replies

kpsyesterday at 5:49 PM

1. That script's color check doesn't check that the output is a terminal. Also test

    tty -s

2. Don't hardcode escape sequences. Use (e.g.)

    export STDOUT_COLOR_START="`tput setaf 4`".
godelskiyesterday at 8:16 PM

That seems needlessly cumbersome, why not

  declare STDOUT_COLOR='\e[34m'
  declare STDERR_COLOR='\e[31m'
  declare COLOR_STOP='\e[0m'

  print_stdout() {
      echo -e "${STDOUT_COLOR}${*}${COLOR_STOP}" &> /dev/stdout
  }

  print_stderrr() {
      echo -e "${STDERR_COLOR}${*}${COLOR_STOP}" &> /dev/stderr
  }
Like why are you exporting? Do you really need those in your environment?

And those print statements aren't going to work by default.

wpmyesterday at 6:39 PM

If you're writing a zsh script and not worried about portability, you can also use the prompt expansion colors with "print".

    print_color () {
      print -P "%F{$1}$2%f"
    }
And then to use it

   print_color "green" "This is printed in green"
show 2 replies
direwolf20yesterday at 5:40 PM

What is the purpose of making everything the same color?

show 1 reply