Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a variable by 0.025 for each loop in BASH (NOT loop variable)

Tags:

bash

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?

like image 841
Amit Avatar asked Mar 02 '11 23:03

Amit


4 Answers

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".

like image 142
DigitalRoss Avatar answered Oct 22 '22 15:10

DigitalRoss


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
like image 43
Dave Jarvis Avatar answered Oct 22 '22 15:10

Dave Jarvis


#!/bin/sh

k=1.00
incl=0.025
k=`echo $k + $incl | bc`

echo $k
like image 28
tsu1980 Avatar answered Oct 22 '22 15:10

tsu1980


Bash doesn't handle floating point math whatsoever. You need help from an external tool like bc.

like image 29
Matt K Avatar answered Oct 22 '22 17:10

Matt K