I've searched for this but can't find anything more than some basic tutorials or posts.
What I'm trying to do is a more sophisticated calculator (without using bc) that can take more than 2 arguments. something like:
./calc.sh 2 + 3 * 7 - 2 ^ 3
My attempt was as follow:
- search for operator
- if operator is ^ or * do the math and replace 2 ^ 2 + 3 * 2 - 2 becomes 4 + 6 -2
- add remains to the list
- next loop checks for : and does the math, same follows for + and -
this leads me to the creation of this piece of "code" but after running it I've realized that there are some major issues with it and swapping deleting items isn't that straightforward to me
#!/bin/bash
initial_data=($@)
result=0
sorted=()
for ((index=0; index <= ${#initial_data[@]}; index++)); do
if [ "${initial_data[index]}" == "^" ]; then
A=${initial_data[index-1]}
B=${initial_data[index+1]}
pow_value=$(($A**$B))
sorted+=$pow_value
elif [ "${initial_data[index]}" == "*" ]; then
C=${initial_data[index-1]}
D=${initial_data[index+1]}
multi_value=`expr $C \* $D`
sorted+=$multi_value
else
normal=${initial_data[index]}
sorted+=$normal
fi
done
echo ${sorted[@]}
then I've scraped this and tried something that goes like this
operators=('^' '*' '/' '+' '-')
data=("$@")
ops=()
for i in "${!data[@]}"; do
if (printf '%s\n' "${operators[@]}" | grep -xq ${data[$i]}); then
ops+=("${data[$i-1]} ${data[$i]} ${data[$i+1]}")
fi
done
declare -p ops
This isn't that bad. It takes the order of operators but I didn't account for odd amount of numbers feed into calc and it doesn't see exponentiation.
I’m bit over my head.