Grunt
Grunt

Reputation: 47

Issue with a Bash loop that uses an integer

So I looked up the examples of a while loop and put the script together as so and still am having issues. If I was to guess I would say it with the arithmetic part of the bc function.

I want the loop to run until I hit a thousand and then count how many times it ran. I am not to the counting part of the script yet as I am still just trying to get it to run (yes I know awk would be easier).

This is what I have so far:

#!/bin/bash
total=120 #this will be a variable that is read in from a menu but 120 is ok for now
while [ $total -lt 1000000 ]
do
echo $total
total=$(bc<<<"scale=2;$total +  $total * .1") #I don't know if I have to use "let" before total but it did not make a difference.
done.

I am getting an error with the line that starts with "total" but the structure of the command seems to fit all the examples I could find. What gives?

Upvotes: 1

Views: 55

Answers (2)

codeforester
codeforester

Reputation: 42999

As long as you are dealing with integers, you can write your loop with the arithmetic expression (( ... )), without the need for an external command like bc:

#!/bin/bash
total=120
while ((total < 1000000)); do
  echo $total
  ((total = total + total / 10))
done

Upvotes: 0

Harvey
Harvey

Reputation: 5821

Use bc for the comparison, too.

#!/usr/bin/env bash

total=120
while [ "$(bc <<< "$total < 1000000")" == 1 ]
do
    echo $total
    total=$(bc <<< "scale=2;$total +  $total * .1")
done

Upvotes: 3

Related Questions