Hey, I just wanted to know how one can write simple arithmetic like addition, subtraction, multiplication and division in shell-script.
matt@matt-macbook$ cat math.sh
#!/bin/sh
NUMBER1=10
NUMBER2=5
((sum=NUMBER1-NUMBER2))
echo $sum
echo "\n"
((difference=NUMBER1-NUMBER2))
echo $difference
echo "\n"
((product=NUMBER1*NUMBER2))
echo $product
echo "\n"
((quotient=NUMBER1/NUMBER2))
echo $quotient
echo "\n"
you can use different commnds such as
1)expr
2)bc
3)shell ("echo $((4+5))")
likewise..
read man page for more info
Thanks. What if I want to perform more than one operation in an equation. Like I want to do (910)/100. I just learnt that expr \ is used for multiplication and expr / for division but the bracket doesn't work here so what do you use instead? Like I want to output (9*10)/100.
Hey sorry, thanks. Without a bracket, it works. So you just say 9*\10 /100.
Just another questions: how can I get the lines of a command in man page. Like I just typed man expr and I want to know the number of lines that come in that command, and then maybe number of the string division in that man page of the command.
Hey I learnt now how to perform basic threat. However I am stuck with doing basic arithmetic for non-integer values. For example I want to perform the operation (120/220) *100.
The shell usually can't do floating-point operations. Use bc for that, eg
VAR=$( echo "(120/220)*100" | bc )
It says non-numeric argument when I try to execute it
What did you try to execute?
$ echo "(120/220)*100" | bc
54.54545454545454545400
$ VAR=$( echo "(120/220)*100" | bc )
$ echo $VAR
54.54545454545454545400
$ div1=120
$ div2=220
$ VAR=$( echo "($div1/$div2)*100" | bc )
$ echo $VAR
54.54545454545454545400
the best is to use awk for any kind of mathematical operation
awk 'BEGIN{print 100/10}'
awk 'BEGIN{print (10/100)*12}' etc etc....
I used the fast one which is
$ echo "(120/220)*100" | bc
but it didn't work. Says command not found.
Then you don't have bc installed. Try the awk approach as suggested by vidyadhar (you can pass variables to awk with the -v switch) or install bc.
How can I install bc then? From the terminal, maybe there is a simple way to do it?
Which OS? In Linux it's one of
- apt-get install bc #Debian & derivates
- zypper install bc #OpenSuSE / SLES
- yum install bc #Red Hat / Fedora / CentOS
- emerge bc #Gentoo
The only common shells that fully support floating point arithmetic are ksh93 and zsh.