I’m new to Bash scripting and trying to write a simple loop, but I keep running into errors. Here’s what I attempted:
let i = $1
while(i < 4); do
echo Hi
((i++))
done
When I run this script with:
$ bash bash_file.sh 0
I get a warning:
bash_file.sh line 2: 4: no such file or directory
I’m confused, why does Bash think a number should be a file or directory?
Also, I’d like to extend this loop so it continues while i < $1 + $2, where $1 and $2 are numbers. How should I write a proper bash while loop for numeric comparisons?
Any guidance or examples for correct syntax would be really helpful.
Bash doesn’t allow C-style parentheses and conditions like while(i < 4) directly. Instead, you can use -lt for “less than” inside square brackets:
i=$1
while [ $i -lt 4 ]; do
echo "Hi"
((i++))
done
This is the most straightforward way I learned early on. Remember: spaces around [ … ] are mandatory, and numeric comparisons use -lt, -gt, -eq, etc.
I often prefer (( … )) for numeric comparisons because it feels cleaner and closer to C-style loops:
i=$1
while (( i < 4 )); do
echo "Hi"
((i++))
done
Here, you don’t need or -lt. This also allows you to write arithmetic expressions directly, so extending the loop condition to $1 + $2 becomes simple:
i=$1
limit=$(( $1 + $2 ))
while (( i < limit )); do
echo "Hi"
((i++))
done ```
If you like using let, the syntax needs to match Bash arithmetic rules. You can write:
let i=$1
while [ $i -lt 4 ]; do
echo "Hi"
let i=i+1
done
From my experience, let works, but the (( … )) syntax is usually preferred because it’s shorter and less error-prone.
Tip: Always make sure numeric variables are initialized properly, and avoid adding spaces around = when assigning (i=$1 is correct; i = $1 is wrong).