mak mak - 1 year ago 90
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 :

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

Anybody cares to improve on this?

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

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 Source
  • 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:

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download