3 ms·
This uses e.g. i=$(($i + 1)) to increment. The simpler and possibly faster way is just ((i++)) or ((i+=1)) This syntax works in macos ksh, so pretty s
by emmelaich 6y ago
This uses e.g. i=$(($i + 1)) to increment.
The simpler and possibly faster way is just
((i++))
or
((i+=1))
This syntax works in macos ksh, so pretty sure it's POSIX.
Also, ksh93 supports sequence generation.. so as an alternative to the loops, use
start=0
end=10
for i in {$start..$end}; do echo $i; done
- fratajcz 6y agoI don't think it's actually specified by POSIX, it only mentions arithmetic expansion with $(()) and there is no mention of (()) for arithmetic operations in the grammar: https://pubs.opengroup.org/onlinepubs/007904875/utilities/xcu_chap02.html#tag_02_10 https://pubs.opengroup.org/onlinepubs/007904875/utilities/xc... The example given for arithmetic expansion also uses x=$(($x-1)): https://pubs.opengroup.org/onlinepubs/007904875/utilities/xcu_chap02.html#tag_02_06_04 https://pubs.opengroup.org/onlinepubs/007904875/utilities/xc...
- emmelaich 6y agoInteresting! I wonder if any shells that support $((..)) do not support ((..) though. The update 2017 standard mentions ((..)) but not in the obvious place. It's under 'compound commands/grouping' ... https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V... > If a character sequence beginning with "((" would be parsed by the shell as an arithmetic expansion if preceded by a '$', shells which implement an extension whereby "((expression))" is evaluated as an arithmetic expression may treat the "((" as introducing as an arithmetic evaluation instead of a grouping command. A conforming application shall ensure that it separates the two leading '(' characters with white space to prevent the shell from performing an arithmetic evaluation.
- Crestwave 6y agoShells such as dash and ash do not support it, which are the most common test cases for POSIX scripts. It should also be noted that pre-increment itself is considered optional by POSIX, although += should work.