Logging and showing colorful bash output

Deploy using the deploy user and also log who deploys using the original user.
Retaining the color was tricky but script fakes tty so we can keep all the color glory and with sed we strip colors before logging them.

# /usr/bin/capsu
function log {
  old_IFS=$IFS
  IFS='' # do not split on newline when reading stdin
  newline=$'\n'
  line=""

  while read -d '' -n1 c # read every character
  do
    # print every character as it comes in for cap shell and password prompts
    printf "%s" "$c"

    # amend complete line with current user (but without color codes) to log
    # so multiple people can run capsu in parallel
    if [ "$c" = $newline ]; then
      echo "$SUDO_USER: $line" | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" >> $1
      line=""
    else
      line+=$c
    fi
  done
  IFS=$old_IFS
}

rvmsudo -u deploy script /dev/null -c "bundle exec cap $@" 2>&1 | log deploy cap.log
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s