I’m trying to replicate the structure of a traditional for loop (like in C or JavaScript) in Bash, something like:
c
Copy
Edit
for (int i = 0; i < MAX; i++) {
doSomething(i);
}
What’s the proper syntax for writing this type of bash for loop, and how do you iterate over a numeric range or list in a shell script?
I’ve written tons of scripts over the years, and honestly, the simplest way I handle a bash for loop is like this:
for i in {0..9}; do
echo "Number: $i"
done
This loops from 0 to 9 (inclusive). It’s super readable and perfect if you’re dealing with small fixed ranges. For most of my everyday scripting, that’s my go-to.
Totally agree, @jacqueline-bosco ! I’ve been scripting in Bash for about 6 years, and when I need more flexibility in my bash for loop, like dynamic ranges, step values, or variables instead of fixed numbers—I switch to the C-style syntax with for (( ))
:
for (( i=0; i<MAX; i++ )); do
echo $i
done
It’s super handy and feels almost identical to C or JavaScript loops. I reach for this when my bounds aren’t hard-coded.
Nice points, both of you! From my experience working on scripts for deploying apps, another angle on the bash for loop is when you’re looping through lists of strings, not numbers. Then I’d go for:
for item in apple banana cherry; do
echo $item
done
It’s clean, easy to read, and perfect for non-numeric lists. But for numeric sequences with steps, Richaa’s for (( ))
definitely gives you the most control in a bash for loop.