user2062275
user2062275

Reputation:

Count down with until

I get the issue when I give the user an option to enter a number, that number is going to be counted down to 1. I'm lost after the echo line, as the script echos the value entered but doesn't count it down to 1.

#!/bin/bash

COUNTER=100
until [  $COUNTER -lt 1 ]; do
read -p "Enter a number between 1-100: " COUNTER
echo COUNTER $COUNTER
let COUNTER-=1
done

Upvotes: 0

Views: 416

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185550

Try doing this using modern :

#!/bin/bash

read -p "Enter a number between 1-100: " counter

until ((counter < 1)); do
    echo "counter $counter"
    ((counter--))
done
  • put read outside of the for loop to do it successfully.
  • avoid using UPPER CASE variables by default, there's reserved for global system variables.
  • ((...)) is more intuitive than -gt, -lt... and is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression

Upvotes: 1

dogbane
dogbane

Reputation: 274758

Move the read out of the loop like this:

read -p "Enter a number between 1-100: " COUNTER    
until [  $COUNTER -lt 1 ]; do
  echo COUNTER $COUNTER
  let COUNTER-=1
done

Upvotes: 1

Related Questions