Search code examples
bashsystemcolors

How to partially change colors of bash command output?


I would like to partially colorize the output of any given bash command in my scripts, just to make it pretty and easy to catch important information displayed on the screen.

It's rather easy to echo colored results, but I failed with commands displaying some system measurements.

Let's use hdparm as an example.

sudo hdparm -t /dev/sda1

will result as follows:

/dev/sda1:

Timing buffered disk reads: 1284 MB in 3.00 seconds = 427.93 MB/sec

I would like "427.93 MB/sec" to be displayed in different color, let's say yellow.

How can I do that?


Solution

  • You can redirect command output into array, and then echo array items in colors you want. For example:

    readarray -d= arr < <(sudo hdparm -t /dev/sda1);echo -e "${arr[0]} \e[31m${arr[1]}}\e[0m"