Tuesday, November 12, 2013

Command line calculator

The basic idea of the following command line calculator is
to perform simple arithmetic operations like


$> c 4 * 5

In this example there are empty spaces around the asterix "*",
which the bash will usually expand to the files in your current directory and
break the calculation.
In the following a variant is present in order to prevent the expansion of the bash:

1. in ~/.alias write

alias c='set -f; call_clc'

2. in ~/.bashrc write

funciton call_clc { clc "$*"; set +f; }

3. create the file ~/bin/clc and write there

echo "$*" | tr -d [:blank:] | bc -l

If the directory ~/bin does not exist, then create it with mkdir ~/bin.
Finally, add export PATH~/bin:$PATH into your ~/.bashrc and execute chmod u+x ~/bin/clc.
Then just source your .bashrc like ". .bashrc" (mind the first and second dot) and your are ready to go.

Now here are other variants, which you could put into your clc file.


# /dev/tty is the userers current shell<br />
echo "$*" | tr -d [:blank:] &>1 | tee /dev/tty | bc

Or another variant with named pipes.


1
2
3
4
5
6
mkfifo pipe
echo "$*" | sed -e 's/ //g' | tee pipe &
pid_pipe=$!
bc &< pipe
wait $pid_pipe
rm pipe

No comments:

Post a Comment