Comment by jph

Comment by jph 3 days ago

7 replies

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.

kps 3 days ago

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`".
godelski 3 days ago

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.

wpm 3 days ago

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"
  • godelski 3 days ago

    Here's something also useful that's portable

      declare GRN='\e[1;32m'
      declare RED='\e[1;31m'
      declare YLW='\e[1;33m'
      declare CYN='\e[1;36m'
    
      write_log() {
          echo -e "[$( date +'%c' )] : ${1}\e[0m" | tee -a ${logfile}
      }
    
      write_log "${RED}I'm an ERROR"
direwolf20 3 days ago

What is the purpose of making everything the same color?