Let's jazz up some Bash scripts today, shall we?
This post was prompted by a forum posting at another site where someone had a script that echoed "Pass' or "Fail" and he wanted "Pass" in green and "Fail" in Red.
By the way, I don't recommend this.
Color is tricky. Displays can be bad at it, people can be color blind... using colors can make text hard to read - I don't like using color in scripts. But, if you insist...
The basic tool for terminal handling is "tput". Put this in a shell script and run it:
For Linux, start up an Xterm or switch to a text console (CTRL-ALT-F1). For Mac OS X, run the Terminal application. You can put these commands in a shell script or just type them.
tput setaf 0;tput setab 7; echo "`tput setaf 1` FAIL `tput setaf 7`" echo "`tput setaf 2` PASS `tput setaf 7`" tput op
Assuming your terminal session can do color, that should have put "FAIL" in red on a white or gray background, "PASS" in green below it and then returned your terminal to its original settings - that is, if you began with a black background and white text, the "tput op" should return you to that, if you had a white background and blue text, you'll be back to that. If for some reason you had a black background with red text, then this didn't change much, did it?
On my screen, both the red and the green are a bit hard to read. I can jazz that up a bit by adding the sequences to start and stop "bold":
echo "`tput setaf 1;tput smso` FAIL `tput rmso;tput setaf 7`"
But it's still not great. If you are tempted to use color in your scripts, I'd suggest doing something like this:
echo "`tput setaf 1` *** `tput op;tput smso`FAIL`tput rmso; tput setaf 1` *** `tput op`"
And honestly I'd rather leave out the bolding.
You can do much more with tput:
This one needs to be in a shell script. If you don't know how to create a shell script, see Scripting - how to write a shell script.
echo "hello" echo "Input please" tput up tput up tput nd tput nd tput nd tput nd tput nd tput nd read akey
You'll see the script waiting for input right next to the "hello". It does that because "tput up" goes up one line, and "tput nd" is a non-destructive backspace. You can even be explicit:
tput cup 10 50;echo "testing 1 2 3"
puts the output at column 50 of line 10. You might want to do "clear" before running that.
To learn even more about what "tput" can do, see "man terminfo" or "info terminfo" (and if you dislike "info", try "pinfo"). To understand more about terminfo and its cousin "termcap", see Termcap and Terminfo .
Got something to add? Send me email.
More Articles by Anthony Lawrence © 2011-03-23 Anthony Lawrence
Show me your flowchart and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won't usually need your flowchart; it'll be obvious. (Fred Brooks, The Mythical Man Month)