Kingamere
Kingamere

Reputation: 10122

bash while loop: No such file or directory

I have a simple bash script:

#!/bin/bash

counter=0
while [ $counter < 100 ]; do
   echo $counter
   counter=$((counter+1))
done

However, when I try to execute this, I get this error:

./test: line 4: 100: No such file or directory

Upvotes: 3

Views: 5766

Answers (2)

Eric Citaire
Eric Citaire

Reputation: 4513

The "less than" operator is -lt, not <.

< will redirect the file contents to the command on the left. That's why you have this error: the file 100 does not exist.

Upvotes: 1

blm
blm

Reputation: 2446

In bash, < redirects standard input, so you're telling bash to read from the file called 100, which doesn't exist. Instead use -lt for comparing numbers.

#!/bin/bash

counter=0
while [ $counter -lt 100 ]; do
   echo $counter
   counter=$((counter+1))
done

Does what you want.

Upvotes: 9

Related Questions