How do I divide in the Linux console?

后端 未结 12 1936
情话喂你
情话喂你 2020-12-25 10:41

I have to variables and I want to find the value of one divided by the other. What commands should I use to do this?

相关标签:
12条回答
  • 2020-12-25 11:19

    Better way is to use "bc", an arbitrary precision calculator.

    variable=$(echo "OPTIONS; OPERATIONS" | bc)
    

    ex:

    my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)
    

    where "scale=5" is accuracy.

    man bc 
    

    comes with several usage examples.

    0 讨论(0)
  • 2020-12-25 11:20

    In bash, if you don't need decimals in your division, you can do:

    >echo $((5+6))
    11
    >echo $((10/2))
    5
    >echo $((10/3))
    3
    
    0 讨论(0)
  • 2020-12-25 11:23

    You can use awk which is a utility/language designed for data extraction

    e.g. for 1.2/3.4

    >echo 1.2 3.4 | awk '{ print $2/$1 }'
    0.352941
    
    0 讨论(0)
  • 2020-12-25 11:25

    I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

    0 讨论(0)
  • 2020-12-25 11:26

    In the bash shell, surround arithmetic expressions with $(( ... ))

    $ echo $(( 7 / 3 ))
    2
    

    Although I think you are limited to integers.

    0 讨论(0)
  • 2020-12-25 11:26

    I still prefer using dc, which is an RPN calculator, so quick session to divide 67 by 18 with 4 digits precision would look like

    >dc
    4k
    67
    18/p
    3.7222
    q
    >
    

    Obviously, much more available: man dc

    0 讨论(0)
提交回复
热议问题