I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
let "k += 0.025"
and
let "$k += 0.025"
and
k += 0.025
and many other variations. Does anyone know how to accomplish this?
You may be working on some giant bash masterpiece that can't be rewritten without a king's ransom.
Alternatively, this problem may be telling you "write me in Ruby or Python or Perl or Awk".
Use integer math and then convert to decimal when needed.
#!/bin/bash
k=25
# Start of loop
#
# Increment variable by 0.025 (times 1000).
#
let k="$k+25"
# Get value as fraction (uses bc).
#
v=$(echo "$k/1000"|bc -l)
# End of loop
#
echo $v
Save as t.sh
, then:
$ chmod +x t.sh
$ ./t.sh
.05000000000000000000
#!/bin/sh
k=1.00
incl=0.025
k=`echo $k + $incl | bc`
echo $k
Bash doesn't handle floating point math whatsoever. You need help from an external tool like bc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With