Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 840
Kingamere Avatar asked Jul 06 '26 12:07

Kingamere


2 Answers

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.

like image 150
blm Avatar answered Jul 08 '26 11:07

blm


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.

like image 34
Eric Citaire Avatar answered Jul 08 '26 09:07

Eric Citaire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!