Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm getting an strange error.

#!/bin/bash
echo "Please enter a number"
read var
declare -i num
num=0
        while ($num<$var)
        do
                echo "$num"
        done

./loop: line 5: 6: No such file or directory

What am i mistaking?

share|improve this question

(...) starts a subshell and runs the specified commands inside it. This is why ($num<$var) generates that error message; it can't find the file corresponding to $var to pass into the command corresponding to $num.

You probably wanted something like

while (( num < var )); do
  echo "$num"
done

((...)) is an arithmetic expansion. It will compute the value of the expression inside. In this case it will compare the values of the two variables (the $ in front of them are not needed here). If the comparison is true, then the while-loop will run one more iteration.

The while-loop is also an endless loop, since you do not increment num nor decrement var.

In the end, you might want to try

for (( num = 0; num < var; ++num )); do
  echo "$num"
done

or

for (( num = 0; num < var; ++num )); do
  printf '%d\n' "$num"
done

If you know C or a language with C-like syntax, then you'll recognize this type of for-loop.

share|improve this answer

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.