1

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?

2
  • There are two lines that start with "total", but I would expect you to get an error on line 3, that starts with While, and I would expect the error to be While: command not found (the keyword "while" is not capitalized). Once that's fixed, I would expect errors about "1,000,000" not being an integer. Commented Apr 26, 2017 at 23:04
  • If I run this at the prompt it works fine but in a loop...not so much total=120 total=$(bc<<<"scale=2;$total + $total * .1");echo $total --and then the output is 132.0 Commented Apr 26, 2017 at 23:04

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

THANKS SOO MUCH! I look forward to be the guy helping out in a few years.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.