I need to add some real numbers in a script. I tried:
let var=2.5+2.5
Run Code Online (Sandbox Code Playgroud)
which gives me an error - invalid arithmetic operator and then I tried:
let var=2,5+2,5
Run Code Online (Sandbox Code Playgroud)
which does not give me an error, but it gives me a wrong result -2 in this case.
Why? How to add real numbers using let or other command?
The first variant (let var=2.5+2.5) doesn't work because bash doesn't support floating point.
The second variant (let var=2,5+2,5) works, but it may not be what you wish because comma has another meaning in this case: it's a separator, command separator. So, your command is equivalent in this case with the following three commands:
let var=2
let 5+2
let 5
Run Code Online (Sandbox Code Playgroud)
which are all valid and because of this you get var=2.
But, the good news is that you can use bc to accomplish what you wish. For example:
var=$(bc <<< "2.5+2.5")
Run Code Online (Sandbox Code Playgroud)
Or awk:
var=$(awk "BEGIN {print 2.5+2.5; exit}")
Run Code Online (Sandbox Code Playgroud)
Or perl:
var=$(perl -e "print 2.5+2.5")
Run Code Online (Sandbox Code Playgroud)
Or python:
var=$(python -c "print 2.5+2.5")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5884 次 |
| 最近记录: |