Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Trying to loop a phrase inputted by the user a set amount of times that is also inputted by the user. Keep on getting the error integer expression expected, and I can't figure out how to fix it.

#!/bin/sh 
echo "What do you want to say?"
read phrase 

echo "How many times?"
read num

while [ "num" -ge 0 ]
do
     echo $phrase
     num='expr num - 1'
done
share|improve this question

2 Answers 2

You need to use a $ to expand a variable in bash, unless it's inside of (( )). You are comparing the literal string "num" to the number 0. Use one of the following:

while [ "$num" -ge 0 ] # POSIX
while (( num >= 0 )); # bash
share|improve this answer

Couple of corrections.

#!/bin/sh
echo "What do you want to say?"
read phrase

echo "How many times?"
read num

while [ $num -gt 0 ];
do
     echo $phrase
     let num='num - 1'
done

Example

$ ./cmd.bash 
What do you want to say?
hi
How many times?
4
hi
hi
hi
hi

You can make the recalculation of $num a little more streamlined and easier to read with this notation.

Change this line:

     let num='num - 1'

with this:

     ( num-- ))

It gets confusing as to when to use or not use the $ notation for variables, generally you'll want to consult the man page for bash and test when doing this kind of work. This change is apt if you're using bash and not just native sh.

Details

  1. You need to use the variable form of $num when performing the bounds check in the while loops control section.
  2. Use let instead of expr.
  3. The bound for the loop is including the 0 step with -ge which will give you 1 more than what you want.

Example

With the while loops bound check using -gt you get this result:

$ ./cmd.bash 
What do you want to say?
hi
How many times?
2
hi
1
hi
0

If you use your -ge you'll get this behavior:

$ ./cmd.bash 
What do you want to say?
hi
How many times?
2
hi
1
hi
0
hi
-1
share|improve this answer
    
Even better than let: (( num++ )) –  jordanm Oct 27 '13 at 3:24
    
@jordanm - thanks I'll change it, I don't do much math in the shell anymore, usually use Perl for this type of stuff 8-) –  slm Oct 27 '13 at 3:25
    
I wouldn't change it, just the comment will do. The OP tagged the question bash but has sh in their shebang. The alternate method I presented won't work in POSIX sh. –  jordanm Oct 27 '13 at 3:26
    
@jordanm - I incorporated it into the answer, but left the original intact as well. –  slm Oct 27 '13 at 3:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.