DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

A Powerful Linux Command Line Calculator Based on bc


Create a shell script named my-calculator.sh under ~/apps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash

# Example: ./my-calculator ih od 23A+34B => echo 'ibase=16;obase=10;23A+34B' | bc
#     where "ih" means "input is hex", "od" means "output is decimal"
#     ./my-calculator ih oh echo 'ibase=16;obase=10;A+A' | bc

if [[ $# -gt 3 ]]; then
    echo Bad format: more than 3 arguments found
    exit 1
fi
in=10
out=10
for op in $@; do
    if [[ $op = 'ib' ]]; then
        in=2
    elif [[ $op = 'id' ]]; then
        in=10
    elif [[ $op = 'ih' ]]; then
        in=16
    elif [[ $op = 'ob' ]]; then
        out=2
    elif [[ $op = 'od' ]]; then
        out=10
    elif [[ $op = 'oh' ]]; then
        out=16
    else 
        expr=$op
    fi
done
echo echo \"obase=$out\;ibase=$in\;$expr\" \| bc
echo "obase=$out;ibase=$in;$expr" | bc

Note: put obase BEFORE ibase, or the obase will based on ibase. For example, the result of

echo "ibase=16;obase=10;A+A" | bc

is 14, but not 20. After "ibase=16", the "10" in "obase=10" is actually a hex, not a decimal. To avoid interfered by ibase, we should always declare obase before ibase.

Now add "alias mc=/home/chad/apps/my-calculator.sh" into your ~/.zshrc, you can do hex calculation by:

$ mc ih oh A+A

Add hex numbers and output to decimal:

$ mc ih A+A

Convert a hex into decimal:

$ mc ih 23B

Convert a decimal to hex:

$ mc oh 23432

Some ordinary decimal calculation:

$ mc 234+345


Published

Apr 30, 2014

Last Updated

Apr 30, 2014

Category

Tech

Tags

  • bc 1
  • calculator 1
  • command line 14
  • linux 158

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor