MJN All Blog Cheatsheets Elasticsearch GCP JS LinuxBash Misc Notes Other ShortcutKeys / - Search

Home / LinuxBash / Script calc - Command line calculator


#!/bin/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
    Convert number to KB, MB, GB, TB, PB.

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

AUTHOR
  mjnurse.dev - 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)
      echo "$help_text"
      exit
      ;;
    -i|--interactive)
      bc -l
      ;;
    -s|--sizes)
      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


This page was generated by GitHub Pages. Page last modified: 22/10/05 13:55