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...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

Most persons avoid dc, since it requires non−intuitive RPN input. Yet it has its uses.<br />

Example 12−36. Converting a decimal number to hexadecimal<br />

#!/bin/bash<br />

# hexconvert.sh: Convert a decimal number to hexadecimal.<br />

BASE=16<br />

# Hexadecimal.<br />

if [ −z "$1" ]<br />

then<br />

echo "Usage: $0 number"<br />

exit $E_NOARGS<br />

# Need a command line argument.<br />

fi<br />

# Exercise: add argument validity checking.<br />

hexcvt ()<br />

{<br />

if [ −z "$1" ]<br />

then<br />

echo 0<br />

return # "Return" 0 if no arg passed to function.<br />

fi<br />

echo ""$1" "$BASE" o p" | dc<br />

# "o" sets radix (numerical base) of output.<br />

# "p" prints the top of stack.<br />

# See 'man dc' for other options.<br />

return<br />

}<br />

hexcvt "$1"<br />

exit 0<br />

Studying the info page for dc gives some insight into its intricacies. However, there seems to be a<br />

small, select group of dc wizards who delight in showing off their mastery of this powerful, but<br />

arcane utility.<br />

Example 12−37. Factoring<br />

#!/bin/bash<br />

# factr.sh: Factor a number<br />

MIN=2 # Will not work for number smaller than this.<br />

E_NOARGS=65<br />

E_TOOSMALL=66<br />

if [ −z $1 ]<br />

then<br />

echo "Usage: $0 number"<br />

exit $E_NOARGS<br />

fi<br />

if [ "$1" −lt "$MIN" ]<br />

Chapter 12. External Filters, Programs and Commands 203

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

Saved successfully!

Ooh no, something went wrong!