Using for Loops Portably
Problem
You need to do a for loop but want it to work on older versions of bash.
Solution
This method is portable back to bash-2.04+:
$ for ((i=0; i<10; i++)); do echo $i; done 0 1 2 3 4 5 6 7 8 9
Discussion
There are nicer ways of writing this loop in newer versions of
bash, but they are not backwards compatible. As of
bash-3.0+ you can use the syntax for {x..y}
, as in:
$ for i in {1..10}; do echo $i; done 1 2 3 4 5 6 7 8 9 10
If your system has the seq command, you could also do this:
$ for i in $(seq 1 10); do echo $i; done 1 2 3 4 5 6 7 8 9 10
See Also
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.