| 1 | #!/bin/bash |
| 2 | # color-echo.sh: Echoing text messages in color. |
| 3 | |
| 4 | # Modify this script for your own purposes. |
| 5 | # It's easier than hand-coding color. |
| 6 | |
| 7 | black='\E[30;47m' |
| 8 | red='\E[31;47m' |
| 9 | green='\E[32;47m' |
| 10 | yellow='\E[33;47m' |
| 11 | blue='\E[34;47m' |
| 12 | magenta='\E[35;47m' |
| 13 | cyan='\E[36;47m' |
| 14 | white='\E[37;47m' |
| 15 | |
| 16 | |
| 17 | alias Reset="tput sgr0" # Reset text attributes to normal |
| 18 | #+ without clearing screen. |
| 19 | |
| 20 | |
| 21 | cecho () # Color-echo. |
| 22 | # Argument $1 = message |
| 23 | # Argument $2 = color |
| 24 | { |
| 25 | local default_msg="No message passed." |
| 26 | # Doesn't really need to be a local variable. |
| 27 | |
| 28 | message=${1:-$default_msg} # Defaults to default message. |
| 29 | color=${2:-$black} # Defaults to black, if not specified. |
| 30 | |
| 31 | echo -e "$color" |
| 32 | echo "$message" |
| 33 | Reset # Reset to normal. |
| 34 | |
| 35 | return |
| 36 | } |
| 37 | |
| 38 | |
| 39 | # Now, let's try it out. |
| 40 | # ---------------------------------------------------- |
| 41 | cecho "Feeling blue..." $blue |
| 42 | cecho "Magenta looks more like purple." $magenta |
| 43 | cecho "Green with envy." $green |
| 44 | cecho "Seeing red?" $red |
| 45 | cecho "Cyan, more familiarly known as aqua." $cyan |
| 46 | cecho "No color passed (defaults to black)." |
| 47 | # Missing $color argument. |
| 48 | cecho "\"Empty\" color passed (defaults to black)." "" |
| 49 | # Empty $color argument. |
| 50 | cecho |
| 51 | # Missing $message and $color arguments. |
| 52 | cecho "" "" |
| 53 | # Empty $message and $color arguments. |
| 54 | # ---------------------------------------------------- |
| 55 | |
| 56 | echo |
| 57 | |
| 58 | exit 0 |
| 59 | |
| 60 | # Exercises: |
| 61 | # --------- |
| 62 | # 1) Add the "bold" attribute to the 'cecho ()' function. |
| 63 | # 2) Add options for colored backgrounds. |