calc - Command line calculator

#!/usr/bin/env bash
help_text="
NAME
    calc - Command line calculator

USAGE
    calc [options] <calculation>

OPTIONS
    -h|--help
        Show help text.

    -i|--interactive
        Launch an interactive (bc) calculator.

    -s|--sizes <value>
        Convert <value> to KB, MB, GB, TB, PB.

DESCRIPTION
    In the calculation use 'x' for multiply, use 'r' for the previous result.

AUTHOR
    mjnurse.github.io - 2020
"
help_line="Command line calculator"
web_desc_line="Command line calculator"
pack_member="default"

try="Try ${0##*/} -h for more information"
tmp="${help_text##*USAGE}"
usage=$(echo "Usage: ${tmp%%OPTIONS*}" | tr -d "\n" | sed "s/  */ /g")

if [[ "$1" == "" ]]; then
  echo "${usage}"
  echo "${try}"
  exit 1
fi

prev_res="$(cat /tmp/calc)"
if [[ "$prev_res" == "" ]]; then
  prev_res=0
fi

while [[ "$1" != "" ]]; do
    case $1 in
        -h|--help) # arg: Show help text.
            echo "$help_text"
            exit
            ;;
        -i|--interactive) # arg: Launch an interactive (bc) calculator.
            bc -l
            ;;
        -s|--sizes) # arg: <value> Convert <value> to KB, MB, GB, TB, PB.
            echo "B : $2"
            echo "KB: $(echo "scale=2; $2/1024" | bc -l)"
            echo "MB: $(echo "scale=2; $2/1024/1024" | bc -l)"
            echo "GB: $(echo "scale=2; $2/1024/1024/1024" | bc -l)"
            echo "TB: $(echo "scale=2; $2/1024/1024/1024/1024" | bc -l)"
            echo "PB: $(echo "scale=2; $2/1024/1024/1024/1024/1024" | bc -l)"
            break
            ;;
        *)
            formula="$(echo $* | sed "s/x/\*/g; s/ //g; s/r/${prev_res}/g")"
            result="$(echo $formula | sed 's/^/scale=3;/ ' | bc -l)"
            echo $formula = $result
            echo "$result" > /tmp/calc
            break
            ;;
    esac
    shift
done