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.

:<br />

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

# Shellscript: base.sh − print number to different bases (Bourne Shell)<br />

# Author : Heiner Steven (heiner.steven@odn.de)<br />

# Date : 07−03−95<br />

# Category : Desktop<br />

# $Id: base.sh,v 1.2 2000/02/06 19:55:35 heiner Exp $<br />

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

# Description<br />

#<br />

# Changes<br />

# 21−03−95 stv fixed error occuring with 0xb as input (0.2)<br />

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

# ==> Used in this document with the script author's permission.<br />

# ==> Comments added by document author.<br />

NOARGS=65<br />

PN=`basename "$0"`<br />

# Program name<br />

VER=`echo '$Revision: 1.2 $' | cut −d' ' −f2` # ==> VER=1.2<br />

Usage () {<br />

echo "$PN − print number to different bases, $VER (stv '95)<br />

usage: $PN [number ...]<br />

If no number is given, the numbers are read from standard input.<br />

A number may be<br />

binary (base 2) starting with 0b (i.e. 0b1100)<br />

octal (base 8) starting with 0 (i.e. 014)<br />

hexadecimal (base 16) starting with 0x (i.e. 0xc)<br />

decimal<br />

otherwise (i.e. 12)" >&2<br />

exit $NOARGS<br />

} # ==> Function to print usage message.<br />

Msg () {<br />

for i # ==> in [list] missing.<br />

do echo "$PN: $i" >&2<br />

done<br />

}<br />

Fatal () { Msg "$@"; exit 66; }<br />

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

PrintBases () {<br />

# Determine base of the number<br />

for i # ==> in [list] missing...<br />

do<br />

# ==> so operates on command line arg(s).<br />

case "$i" in<br />

0b*) ibase=2;; # binary<br />

0x*|[a−f]*|[A−F]*) ibase=16;; # hexadecimal<br />

0*) ibase=8;; # octal<br />

[1−9]*) ibase=10;; # decimal<br />

*)<br />

Msg "illegal number $i − ignored"<br />

continue;;<br />

esac<br />

# Remove prefix, convert hex digits to uppercase (bc needs this)<br />

number=`echo "$i" | sed −e 's:^0[bBxX]::' | tr '[a−f]' '[A−F]'`<br />

# ==> Uses ":" as sed separator, rather than "/".<br />

# Convert number to decimal<br />

dec=`echo "ibase=$ibase; $number" | bc` # ==> 'bc' is calculator utility.<br />

Chapter 12. External Filters, Programs and Commands 198

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

Saved successfully!

Ooh no, something went wrong!