![]() ESN 96188-091108-879021-66 |
|
Document Name: Using color in shell scripts (Linux, Mac OS X) Document Description: Using color in shell scripts (Linux, Mac OS X)2009/11/08Let'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. 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": But it's still not great. If you are tempted to use color in your scripts, I'd suggest doing something like this: 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. 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: 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 . If you dislike Linux colorization (I do!), see Controlling Linux colors in vi (vim). Author: Anthony Lawrence - Contact Author Publisher: Anthony Lawrence Licensee Name: Anthony Lawrence Reference URL: http://aplawrence.com/Linux/setting-colors.html Copyright: All Rights Reserved Registration Date: 11/8/2009 12:29:19 PM UTC Views: 790 |
