0

I supossed to make a script that given an number it count to 0, I managed to do this and it's working:

#!/bin/bash
echo -n "type a number: "
read number; echo
while [ $number -ge 0 ]; do
echo -n "$number"
number=$((number-1))
done
echo

Well, I changed it because I need to pass the number by an parameter ex: "./script 5" and it must show the countdown till 0, but its getting in looping. I kind new on all it script/stack what Im doing wrong?

#!/bin/bash
if [ "$*" = "" ]; then
echo
echo "not correct"
echo "must be a int number"
echo
exit
fi

while [ "$1" -ge 0 ]; do
echo "$1"
cont='expr $1-1' 
done
echo
1
  • I'm not sure that an issue that surrounds modifying a different variable than the one you test to determine whether to terminate your loop is an issue likely to be helpful to others, and thus a useful knowledgebase addition. Commented Dec 6, 2015 at 16:34

1 Answer 1

2

You're always using [ "$1" -ge 0 ] as your condition, but the value you actually modify/update is cont, not $1. (Moreover, you modify it based on the value of $1, which isn't changing, so you only ever set $cont to one less than the original value of $1).

Consider:

#!/bin/bash
[[ $1 ]] || { printf '%s\n' "First argument must be an integer" >&2; exit 1; }
for ((i=$1; i>=0; i--)); do
    echo "$i"
done

...and note, among the various changes:

  • We're consistently referring to the first argument passed as $1, rather than also sometimes referring to it as $*
  • When we select a variable to modify ($i, here, rather than $cont), we use that same variable in our tests, and also as the source for modification in the loop.
  • Using expr for math is antiquated; POSIX sh allows $(( )) to create a math context, and bash extends this to also allow C-style for loops in a math context.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.