Thursday 31 August 2017

Adding color to your commands with tput and echo



In a previous article I demonstrated how we could modify the color of the text being displayed on the command line using printf and ANSI escape sequences.

In this article, using those same escape codes I'll show you how we would use echo instead of printf and also use the tput command to change color.

While working with printf in the previous article I printed out some random text but here we'll be using command line substitution to add color to commands.

Before the examples, let's have a look at the ANSI escape sequences reference table:


Now, let's look at the first example using echo:

[root@pbox ~]# echo -e "\033[34m$(cat list)\033[00m"



The equivalent printf rendition would be as follows:

printf "\033[34m$(cat list)\033[00m"


Next we have a look at tput. The tput command in a nutshell gives the shell the ability to access and modify values of some of the terminal dependent capabilities.

tput setaf 3 ; cat /etc/hosts;tput setaf 7



Using the tput command with the setaf option and giving it the argument 3 gives the subsequent typed commands a yellow color. Setting the value to 7 returns the tex color to the default white.

I took screenshots of how the text changed color as I changed the numeric value of the argument being passed to tput setaf



We dived into a small subset of tput's capabilities. Consider going through this link to learn more about tput.

I've been told that tput's behavior is not consistent across platforms. So if you want to use color coded content in your scripts I'd recommend sticking to echo and printf in the interest of portability of the code.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...