How to use less with colored output

2 min read | by Jordi Prats

If we try to use less on an application with colored output it will get messy like this:

$ terraform plan | less
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  ESC[33m~ESC[0m update in-place
Terraform will perform the following actions:

ESC[1m  # module.spinnaker.kubernetes_default_service_account.default_saESC[0m will be updated in-placeESC[0mESC[0m
ESC[0m  ESC[33m~ESC[0mESC[0m resource "kubernetes_default_service_account" "default_sa" {
        ESC[1mESC[0midESC[0mESC[0m                              = "spinnaker-green/default"
        ESC[90m# (2 unchanged attributes hidden)ESC[0mESC[0m

      ESC[31m-ESC[0m ESC[0msecret {
          ESC[31m-ESC[0m ESC[0mESC[1mESC[0mnameESC[0mESC[0m = "default-token-m2z4q" ESC[90m->ESC[0m ESC[0mESC[90mnullESC[0mESC[0m
        ESC[90m# (1 unchanged block hidden)ESC[0mESC[0m

ESC[0mESC[1mPlan:ESC[0m 0 to add, 1 to change, 0 to destroy.


Some applications, like terraform might have a flag to disable the colored output. For example, to disable coloring on terrafrom we need to add the -no-color option:

$ terraform plan -no-color | less

But if we want to be able to see the colors on less paged output, we will have to add the --raw-control-chars flag (-r for short) So using less like this we will be able to see the color output being paged:

$ terraform plan | less -r

Posted on 22/10/2021