This is the way I'd do it:
Code:
#!/bin/bash
function die () {
echo "$1"
exit 1
# it's better to exit with an error code other than zero,
# this way, external programs can know whether this succeeded
# or not :)
}
function convert() {
number=$( echo "$3" | tr -s '[:lower:]' '[:upper:]' )
result=$(echo "obase=$2;ibase=$1;$number" | bc)
if [ ! "$?" == "0" ]; then
die "bc error: wrong values."
fi
echo "Original number in base $1: $number"
echo "Converted number in base $2: $result"
}
# Error checking
if [ $# = 0 ]; then die "You didn't specify any arguments."; fi
# Defaults
inType=10
outType=16
while [ -n "$1" ]; do
case "$1" in
-i|--input-base)
if [ -n "$2" ]; then
inType="$2"
else
die " $1 requires an aditional parameter."
fi
shift; shift;
;;
-o|--output-base)
if [ -n "$2" ]; then
outType="$2"
else
die " $1 requires an aditional parameter."
fi
shift; shift;
;;
*)
convert $inType $outType $1
shift;
;;
esac
done
Case along with shift let you handle the arguments in a smarter and more flexible way (you can use -i and -o on any order, as long as the following argument is the base). Note that it will also convert as many numbers as desired on a single run:
Code:
bconvert -o 3 108762345243 42352453 524352453
Original number in base 10: 108762345243
Converted number in base 3: 101101201211112121020000
Original number in base 10: 42352453
Converted number in base 3: 2221200201122101
Original number in base 10: 524352453
Converted number in base 3: 1100112122212100020
It's better to use different argument names for different arguments. Your original design is prone to confusion in that regard because the arguments to determine inType and outType are named the same. This script should handle any base, and not just 8, 10 and 16. It also has defaults for inType and outType so you don't forcingly have to specify none.
What could be enhanced? Well, the error handling could be better. Also you could add a -h|--help clause in the case statement. The help text could be designed as a function (you already have two examples in that code), a function that should be called either when you use -h or --help or when you invoke the program without arguments. Designing it as a function let's you call it from many places without having to duplicate the code. You could as well add -idec, -ihex, -ibin, -ioct, -ooct, -odec, -ohex, -obin parameters that would be shorthands for these common bases.
This is a quick adaptation so it might have some flaws that I haven't yet considered.
EDIT: fixed.