echo "enter number"
read num1
echo "enter number"
read num2
#originally i had
answer=`expr $num1 / $num2`
#this didn't work with decimals or if num1 was the smaller number
echo "The result is " $answer
# but did out put the way i needed if num1 was larger, else I got 0, so changed code to
"scale=2 ; $num1 / $num2" | bc
#got right calc - can input any number
#Need to pass calc result to variable called answer then call echo "the result is " $answer
#can't seem to work it out
Asked
Active
Viewed 137 times
0

oguz ismail
- 1
- 16
- 47
- 69

Donski72
- 1
- 1
-
BTW, `expr` is best avoided in general -- since the early-1990s publication of the POSIX.2 standard, `answer=$(( num1 / num2 ))` has been standardized math syntax guaranteed in all POSIX-compliant shells; and using the built-in syntax is much more efficient than calling a program like `expr`. Since the standard syntax is still integer-only, you _do_ still need `bc` in this case -- so as far as I can tell, the only problem at hand here is not knowing how to store its output in a variable. That's the same as storing _any other program_'s output in a variable, hence the close-as-duplicate. – Charles Duffy Sep 29 '21 at 13:45
-
Another note -- one place where bash is quite different from other languages is that quotes don't just define where constant strings begin and end -- they also determine how expansions are processed. You generally want all command substitutions and parameter expansions (aka variable expansions) to be inside double quotes; so `echo "The result is $result"`, or `echo "The result is $(bc <<<"scale=2; $num1 / $num2")"`. Otherwise you get into trouble -- try comparing `result='*'; echo "The result is" $result` against `result='*'; echo "The result is $result"`. – Charles Duffy Sep 29 '21 at 13:46
1 Answers
0
Hej, you need to echo your result like this:
#!/bin/bash
echo "enter number"
read num1
echo "enter number"
read num2
echo "The result is "
echo "scale=2 ; $num1 / $num2" |bc

consumere
- 1
- 1
-
See the _Answer Well-Asked Questions_ section of [How to Answer](https://stackoverflow.com/help/how-to-answer) -- questions that have been "asked and answered many times before" should be closed as duplicate rather than having new answers given. – Charles Duffy Sep 29 '21 at 13:43
-
Also, this isn't doing what the question asked for -- it isn't storing the result in a variable. The OP wants the answer to be _on the same line_ as the header introducing it. – Charles Duffy Sep 29 '21 at 13:43