27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

#!/bin/bash<br />

# color−echo.sh: Echoing text messages in color.<br />

# Modify this script for your own purposes.<br />

# It's easier than hand−coding color.<br />

black='\E[30;47m'<br />

red='\E[31;47m'<br />

green='\E[32;47m'<br />

yellow='\E[33;47m'<br />

blue='\E[34;47m'<br />

magenta='\E[35;47m'<br />

cyan='\E[36;47m'<br />

white='\E[37;47m'<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

alias Reset="tput sgr0"<br />

# Reset text attributes to normal<br />

#+ without clearing screen.<br />

cecho ()<br />

# Color−echo.<br />

# Argument $1 = message<br />

# Argument $2 = color<br />

{<br />

local default_msg="No message passed."<br />

# Doesn't really need to be a local variable.<br />

message=${1:−$default_msg}<br />

color=${2:−$black}<br />

echo −e "$color"<br />

echo "$message"<br />

Reset<br />

# Defaults to default message.<br />

# Defaults to black, if not specified.<br />

# Reset to normal.<br />

}<br />

return<br />

# Now, let's try it out.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

cecho "Feeling blue..." $blue<br />

cecho "Magenta looks more like purple." $magenta<br />

cecho "Green with envy." $green<br />

cecho "Seeing red?" $red<br />

cecho "Cyan, more familiarly known as aqua." $cyan<br />

cecho "No color passed (defaults to black)."<br />

# Missing $color argument.<br />

cecho "\"Empty\" color passed (defaults to black)." ""<br />

# Empty $color argument.<br />

cecho<br />

# Missing $message and $color arguments.<br />

cecho "" ""<br />

# Empty $message and $color arguments.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

echo<br />

exit 0<br />

# Exercises:<br />

# −−−−−−−−−<br />

# 1) Add the "bold" attribute to the 'cecho ()' function.<br />

Chapter 34. Miscellany 345

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!