0

I need a bash script that calculates basic tax. It should be callable by

tax.sh or with an optional parameter: tax.sh (capital or help) (interest rate) (duration)

What I have is that:

re='^-?[0-9]+([.][0-9]+)?$'
echo "capital: "
read capital
if ![[ $capital =~ $re ]] ; then
  echo "invalid capital!" >&2; exit 1
fi
echo "rate: "
    read rate
    if ![[ $rate=~ $re ]] ; then
      echo "invalid rate!" >&2; exit 1
    fi
echo "duration: "
    read duration
    if ![[ $duration=~ $re ]] ; then
      echo "invalid duration!" >&2; exit 1
    fi
echo "the capital after "$duration" years is: "
echo "scale=5;($capital*($rate/100)*$duration)+$capital" | bc

I have no clue how to implement parameters or do the calculation right :/ The calculation is always a little bit smaller then it should be.

  • What is your question here? your script seems ok, except few syntax error instances leaving a space in `![[ $rate=~ $re ]] ;` to `! [[ $rate =~ $re ]] ;` – Inian Dec 06 '16 at 13:31
  • "The calculation is always a little bit smaller then it should be.". Examples? – Ruslan Osmanov Dec 06 '16 at 13:31
  • e.g. 5000 1 5 should be 5255.05 but it is 5250 in the shell script. and the 2nd question is how I implement the parameters – Dimitri Strogatrov Dec 06 '16 at 13:34
  • @DimitriStrogatrov: What is the `$tax` variable doing in the calculation? It has not been read or set before? – Inian Dec 06 '16 at 13:48
  • sorry that actually was a typing error of me... i meant $rate there. happened when copying from putty... – Dimitri Strogatrov Dec 07 '16 at 19:35
  • I suspect the reason the answer is too small is because the formula assumes simple interest but compound interest is required. A different formula must be used. As for parameters, see [How to pass parameters to a Linux Bash script?](http://stackoverflow.com/q/2645636/4154375). – pjh Dec 07 '16 at 20:10

1 Answers1

0

how to implement parameters

A way is to assign positional parameters to your variables and skip the read of each variable if the parameter is not null; e. g.

capital=$1; ${capital:+:} read -p "capital: " capital
…
rate=$2; ${rate:+:} read -p "rate: " rate
…
duration=$3; ${duration:+:} read -p "duration: " duration
…

do the calculation right

As pjh rightly wrote: "the reason the answer is too small is because the formula assumes simple interest but compound interest is required. A different formula must be used." This is:

echo "scale=5;$capital*(1+$rate/100)^$duration" | bc
Armali
  • 18,255
  • 14
  • 57
  • 171