Counting down in a loop to zero by the number being given

Mark picture Mark · Apr 18, 2015 · Viewed 11.5k times · Source

I am trying to write a while loop to determine the number is being given to count down to 0. Also, if there's no argument given, must display "no parameters given.

Now I have it counting down but the last number is not being 0 and as it is counting down it starts with the number 1. I mush use a while loop.

My NEW SCRIPT.

 if [ $# -eq "0" ] ;then
       echo "No paramters given"
 else
       echo $#
  fi

 COUNT=$1
 while [ $COUNT -gt 0 ] ;do
         echo $COUNT
         let COUNT=COUNT-1
  done
  echo Finished!

This is what outputs for me.

 sh countdown.sh 5
1
5
4
3
2
1
Finished!

I need it to reach to 0

Answer

mklement0 picture mklement0 · Apr 18, 2015

@Slizzered has already spotted your problem in a comment:

  • You need operator -ge (greater than or equal) rather than -gt (greater than) in order to count down to 0.
  • As for why 1 is printed first: that's simply due to the echo $# statement before the while loop.

If you're using bash, you could also consider simplifying your code with this idiomatic reformulation:

#!/usr/bin/env bash

# Count is passed as the 1st argument.
# Abort with error message, if not given.
count=${1?No parameters given}

# Count down to 0 using a C-style arithmetic expression inside `((...))`.
# Note: Increment the count first so as to simplify the `while` loop.
(( ++count )) 
while (( --count >= 0 )); do
  echo $count
done

echo 'Finished!'