mak mak - 3 months ago 9
Bash Question

What is the most portable way to write an iteration (for, while) loop in a (POSIX) shell script?

From what I've read on stack, here's one syntax :

iterator=0
while [ "$iterator" -lt 100 ]
do
printf "$iterator"
iterator=`expr $iterator + 1 `
done


Anybody cares to improve on this?

Aim is to make an iteration loop that would be most portable on posix systems.

[EDIT]
just found this question which has very relevant answers:
How do I iterate over a range of numbers defined by variables in Bash? but I'd like an answer here because I believe my question is more precise for future searches.

Answer
  • You probably want a newline in the printf format; otherwise, the numbers are all printed on a single line with no spacing.

  • You should use $(…) in place of the back-ticks.

  • Even POSIX shells support iterator=$(( $iterator + 1 )) (where the $(( … )) notation is distinct from the $( … ) notation!), so you don't need to use expr.

Putting those together:

iterator=0
while [ $iterator -lt 100 ]
do
    printf '%d\n' $iterator
    iterator=$(( $iterator + 1 ))
done

There are other options if you have a command such as seq available, but that isn't a part of POSIX.

There are those who would demand that the variables be enclosed in quotes when referenced. There's no harm in doing so, and in much general code, I would do so. But here the values are strictly controlled by the script; there is no way for blanks or other awkward characters to get in the way of the correct operation of the script.

Comments