bash bc divide script_Any more simple equivalents?
MAIN QUESTION:
I would like to make a bash script that can divide two integers. After a lot of failure, I read http://www.linuxquestions.org/questi...ulator-602583/ and finally succeeded with: Code:
result=$(echo "scale=2; $num1/$num2" |bc); Many noob bash learners like I experience lower retention/slower learning rates when using compound/complex statements from the start. However, when we can separate different ideas onto each line, than we learn quicker/higher retention rates. #BACKUP INFO: #1) I also read the tutorial on http://www.novell.com/coolsolutions/tools/17043.html, but #this solution merely solves the problem by changing your single computers' bash settings, #thus is not cross platform. #2)Entire script: Code:
#!/bin/bash |
What you probably want are the rules for ARITHMETIC EXPANSION and ARITHMETIC EVALUATION from the bash man page.
In particular, you need to see the syntax for the let statement, and its equivalent ((...)). To get you going, start here in man bash: Code:
Compound Commands Here is a free example to jump-start you: Code:
#!/bin/bash |
As per astrogeek's examples, shell built-ins only do integer calcns, which means if you want non-int answers eg during division, then you'll need an external cmd like bc.
Here's a very good page http://www.basicallytech.com/blog/ar...ions-using-bc/ |
Nice tutorial suggestion
Quote:
Code:
result=$(echo "scale=2; $num1/$num2" |bc); |
I think its due to the fact that bc is in fact an interactive tool (page down a bit) so you have to 'cheat' a bit to get non-interactive usage as well.
|
You can eliminate the echo command and use a "here string":
Code:
bc <<<"scale=2; $num1/$num2" |
Quote:
Code:
coproc bc # start bc |
Quote:
Code:
a@NP-NC110:~$ sudo apt-get install coproc |
Quote:
|
All times are GMT -5. The time now is 06:45 PM. |